fcompop is a library for function composition, the README demonstrates the following example:
>>> import fcompop >>> # adding operators to builtin&user functions >>> fcompop.inject() >>> func = str._ >> (lambda x: x * 2 + 'abc') >> str.upper >>> func(123) '123123ABC' >>> func = (lambda x: '-' + x)._ << chr << \ ... (lambda x: x + 1) << ord >>> func('a') '-b'
I really don’t know anything about functional programming, but some real world example would be better to understand, or at least to see. There must be a much better example, but the following is all I could come up with:
>>> adder = lambda addition: lambda x: x + addition >>> multiplier = lambda multiplication: \ ... lambda x: x * multiplication >>> f2c = float._ >> adder(-32) >> multiplier(5.0 / 9.0) >> \ ... "In Celsius, it's {} degree.".format >>> f2c(212) "In Celsius, it's 100.0 degree."
And yes, one lambda can achieve all these, that’s why I said there must be a better example for real and practical usage.
f2c = lambda f: "In Celsius, it's {} degree.".format( float(f) - 32 * 5 / 9)
fcompop is written by Jun Namikawa under the ISC License, currently version 0.3 (2014-05-14), for both Python 2 and 3.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.