Hacker News new | past | comments | ask | show | jobs | submit login
Functional programming with python (united-coders.com)
27 points by Anon84 on April 17, 2009 | hide | past | favorite | 13 comments



Newer versions of Python also have generator expressions which look similar to list comprehensions but with parenthesis instead of brackets. They mostly can be used for similar purposes but they are lazy, that is they only generate results as they are requested.


The keyword 'yield' comes in handy for making your own generators.


Offtopic: I recommend picking up Expert Python Programming by Tarek Ziadé if you want to get a feel for what is 'Pythonic'.


Guido wanted to kick out map and filter in Python 3000 but there was community out there using these two, God knows for what reasons. As long as the lambda is limited to single expressions, map and filter are pretty much useless; and lambda is going to stay like that due to the way Python handles scoping using indentation.


> As long as the lambda is limited to single expressions, map and filter are pretty much useless

Not really. It is not too difficult to actually define a named function and the code usually ends up being easier to read/understand so that lack of multi-line lambdas is not a serious problem. Additionally, now that map and filter return iterators they are a bit more flexible than they used to be. OTOH, if you are using map and filter in your python code you should probably take a close look at what you are attempting to accomplish and see if a generator expression might do the job better.


He didn't want to remove them, he just wanted to move them out of the global namespace.


Should we tell the author that 'reduce' was removed in Python 3?


reduce is still available in the functools module. Also map and filter are lazy in Python 3; they return generators instead of lists.


Ironically, map and filter are still available, when they seem easily duplicatible with comprehensions:

  map(f,lst) = [f(x) for x in lst]
  filter(f,lst) = [x for x in lst if f(x)]
But I don't see a way to translate reduce, except for perhaps the particular case of sum.

  reduce(f,lst) = ???


Write a for loop. Much of the time, the code ends up clearer.

See Guido's explanation at: http://www.artima.com/weblogs/viewpost.jsp?thread=98196


Thank you. I picked up Python from assorted online tutorials; maybe it's time for me to look at the book mentioned elsewhere in this thread to improve my style.


There existsa reason: the map/filter version can improved with a threaded map/filter variant, the list comprehension line not.

And yes, a list comprehension produce a list with the same length, reduce not.


Nice little introduction! I wish I had read something like that when I first started with Python.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: