Search code examples
pythonhaskellclojurefunctional-programminglist-comprehension

What is a solid example of something that can be done with list comprehensions that is tricky with high order functions?


I've heard from many Pythonists that they prefer list comprehensions because they can do everything you can do using high order functions such as filter and reduce, and more. So this question address them: what is a solid example of something you can do with them, that is tricky to do with HOFs?


Solution

  • The answer is that there is no such example. Everything you can do with list comprehensions has a mechanical translation to higher-order functions. In fact, this is how Haskell implements list comprehensions: it desugars them to higher-order functions.

    Given a list comprehension like this:

    [(x, y) | x <- [1..3], y <- [4..6]]
    

    Haskell desugars it to:

    concatMap (\x -> concatMap (\y -> [(x, y)]) [4..6]) [1..3]
    

    Similarly, if you put in predicates like:

    [(x, y) | x <- [1..3], y <- [4..6], x + y /= 5]
    

    ... then that desugars to:

    concatMap (\x -> concatMap (\y -> if (x + y) == 5 then [(x, y)] else []) [4..6]) [1..3]
    

    In fact, this desugaring is part of the Haskell specification, which you can find here.