Functional composition in python
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Aug 28 21:14:56 EDT 2010
On Sat, 28 Aug 2010 21:30:39 +0400, Dmitry Groshev wrote:
> Hello all. Some time ago I wrote a little library:
> http://github.com/si14/python-functional-composition/ , inspired by
> modern functional languages like F#. In my opinion it is quite useful
> now, but I would like to discuss it.
> An example of usage:
>
> import os
> from pyfuncomp import composable, c, _
>
> def comment_cutter(s):
> t = s.find("#")
> return s if t < 0 else s[0:t].strip()
>
> @composable #one can use a decorator to make a composable function
> def empty_tester(x):
> return len(x) > 0 and x[0] != "#"
Why do you need a decorator to make a composable function? Surely all
functions are composable -- it is the nature of functions that you can
call one function with the output of another function.
> path_prefix = "test"
>
> config_parser = (c(open) >> #or use a transformer function
> c(str.strip).map >> #"map" acts like a function modifier
> c(comment_cutter).map >>
> empty_tester.filter >> #so does "filter"
> c(os.path.join)[path_prefix, _].map) #f[a, _, b] is
> used to make a partial.
> #f[a, foo:bar,
> baz:_] is also correct
>
> print config_parser("test.txt")
> print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1,
> 2, 3])
>
> Any suggestions are appreciated.
Did you expect us to guess what the above code would do? Without showing
the output, the above is just line noise.
What does c() do? What does compose() do that ordinary function
composition doesn't do? You say that "map" acts as a function modifier,
but don't tell us *what* it modifies or in what way. Same for filter.
So anyone not familiar with C syntax, the use of << is just line noise.
You need to at say what you're using it for.
--
Steven
More information about the Python-list
mailing list