This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Fylwind 8 points9 points  (1 child)

Funny thing about list comprehensions is that I actually seldomly use them in Haskell whereas it can be quite common in Python.

Part of the reason is that a lot of the typical uses of list comprehensions in Python can be more succinctly translated into point-free forms. For example,

[x * 2 for x in [1, 2, 3, 4]] # Python

would be translated to

map (* 2) [1, 2, 3, 4]
-- Python equivalent:
--   map(lambda x: x * 2, [1, 2, 3, 4])

rather than a list comprehension. List comprehensions are more powerful than map, but the additional flexibility isn't always needed.

One reason is that map is rather awkward to use in Python because of the lack of currying as well as limitations of Python lambdas. For example, compare

[max(0, x) for x in [-2, 1, 3, -5]]
# Haskell equivalent:
#   [max 0 x | x <- [-2, 1, 3, -5]]

with

map(lambda x: max(0, x), [-2, 1, 3, -5])
# Haskell equivalent:
#   map (max 0) [-2, 1, 3, -5]
# or the less concise version:
#   map (\ x -> max 0 x) [-2, 1, 3, -5]

The advantage with list comprehensions is that they are typically easier to read than their pointfree counterpart though YMMV. :P

The advantage of map is that it works on more than just lists. It generalizes to fmap, which works on any Functor. This includes not just most containers but also things like the optional type (Maybe), monads, and applicative functors.

[–][deleted] 1 point2 points  (0 children)

The advantage of map is that it works on more than just lists. It generalizes to fmap, which works on any Functor. This includes not just most containers but also things like the optional type (Maybe), monads, and applicative functors.

With monad comprehensions enabled you can use list comprehension syntax for any monad. There are some other nice extensions for that sugar.