Skip to content

Comment on List Comprehensions in Eight Lines of Clojureparent

Comments

I don't think you understand what was claimed in the article. 'List comprehension' is the name of a specific syntactic construct. List comprehensions describe straightforward transformations of other lists in convenient notation. http://en.wikipedia.org/wiki/List_comprehension

They're syntactic sugar for map and filter. Consider this python code:

    [x**2 for x in range(100) if x % 2 == 1]
This is a list comprehension. It's equivalent (in 2.x) to the Python
    map(lambda x: x**2, filter(lambda x: x%2 == 1, range(100)))
(or in Clojure,
    (map #(* % %) (filter #(= 1 (mod % 2)) (range 100)))
(seems like cheating to use the odd? function))

...so, equivalent to map and filter, just with better syntax.

Caveat: in 3.x, python's map and filter return generators, so the equivalent comprehension would be a generator comprehension instead--just the same thing as above but wrapped in parens and not square brackets--which would also return a generator.

You forget monads. Much brighter people already done this in comments above.)

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.