TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Charming Python: Functional programming in Python

61 pointsby m3mb3rover 14 years ago

8 comments

gcrover 14 years ago
This article was written in 2001, and python now includes first-class constructs for many of these.<p>Map:<p><pre><code> &#62;&#62;&#62; [ord(char) for char in "Hello"] [72, 101, 108, 108, 111] </code></pre> Filter:<p><pre><code> &#62;&#62;&#62; [x for x in xrange(10) if x % 2] [1, 3, 5, 7, 9] </code></pre> For laziness, use parenthesis to turn the above list comprehensions into a generator comprehension. Though I don't demonstrate it, you can work over infinite sequences of objects this way with constant memory usage (without allocating all of them upfront).<p><pre><code> &#62;&#62;&#62; gen = (x for x in range(10) if x % 2) &#62;&#62;&#62; gen &#60;generator object &#60;genexpr&#62; at 0xb729f6bc&#62; &#62;&#62;&#62; for element in gen: ... print element ... 1 3 5 7 9 </code></pre> Alice, the rabbit hole begins here --&#62; <a href="http://docs.python.org/library/itertools.html" rel="nofollow">http://docs.python.org/library/itertools.html</a>
评论 #2030950 未加载
评论 #2031000 未加载
koenigdavidmjover 14 years ago
They are using the old 'foo and bar or baz' style as a cheap substitute for the ternary operator. That should be 'bar if foo else baz' in modern Python.
评论 #2030033 未加载
RyanMcGrealover 14 years ago
Note:<p>&#62; Date: 01 Mar 2001<p>Some of this advice is deprecated.
CrLfover 14 years ago
Although I'm fond of using some functional constructs where they make sense, I don't like functional languages and this article is an example of why: in search for a functional style, clear code becomes opaque and simple code becomes complex.
albemuthover 14 years ago
I think more people would read more ibm dev articles if they changed the css a little bit
评论 #2030642 未加载
barnabyover 14 years ago
Is there an updated version of this? Would be really good to see the full list of improvements in this space.
Swizecover 14 years ago
Ever since I've dabbled a bit with Lisp my Python (and javascript) code has become much more functional-y.<p>Still not sure whether this is a good or bad thing.
评论 #2029918 未加载
评论 #2029850 未加载
exitover 14 years ago
why doesn't python have anonymous functions (not just lambdas which can only be expressions)?
评论 #2029887 未加载
评论 #2029909 未加载
评论 #2029832 未加载