Live data from Hacker News

Functional Programming in Python [pdf]

oreilly.com

61–62 of 62 posts

Re: Functional Programming in Python [pdf]

#61

Nice, short little book! `compose` can be simpler: def compose(fn, *fns): def _composer(f, g): return lambda *args: f(g(*args)) return reduce(_composer, fns, fn) This little function is really, really cool because it allows you to build up more interesting functions by piecing together a bunch of small, useful ones. def upper(s): return s.upper() def exclaim(s): return s + '!' # instead of this really_angry = lambda…

I started with something like that when I was missing function composition in Python. Eventually I ended up with a library [1] including a bunch of other stuff for getting rid of some of the duct tape code you usually need when you just want to compose some functions.

  from pipetools import pipe, X, foreach

  really_angry = pipe | upper | exclaim | exclaim
or...

  really_angry = X.upper() | "{0}!" | "{0}!"


  (1, 2, 3, 4) > foreach((X + 1) | (X * 3)) | max 

You can write some pretty neat looking concise code with this, but also may regret it later when it comes to debugging, especially when lazy evaluation is involved (which is usually the case). The stacktraces tend to be not so helpful...

[1] https://0101.github.io/pipetools/

Re: Functional Programming in Python [pdf]

#62

Yeah. Python has the functional programming features I expect of any modern language. However, I feel that Python has a lot of unneeded syntax. I always prefer apply() over * and map() and filter() over list comprehensions. func(*args) apply(func, args) [func(a) for a in collection] map(func, collection) [a for a in collection if func(a)] filter(func, collection) I don't see why people use all of this special syntax.

  [(foo(a), bar(a)) for a in collection if condition(a) or alt(a)]

  foo_bar = lambda x: (foo(x), bar(x))
  condition_or_alt = lambda x: condition(x) or alt(x)
  map(foo_bar, filter(condition_or_alt, collection))
As logic gets more complicated, wouldn't list comprehensions become easier to read straight through?
Post reply on HN