In my previous blog entry, I shared some findings on creating lists with list comprehensions. I had a further look on this and how to use map and filter functions for list creation with list comprehensions. For example, in Python you can map a function to list entries to generate more specific lists as follows.
l1 = [x * x for x in range(5)] l2 = [hex(x) for x in range(5)]
Applying a filter during list creation is easy as well. The following creates a list with even entries only.
l3 = [x * x for x in range(5) if (x * x) % 2 == 0]
Let’s see how it works in Haskell.
l1 = [x*x | x <- [0..4]] l3 = [x*x | x <- [0..4], even (x*x)]
Looks pretty straightforward to me. And what about F#?
let l1 = [for x in 0..4 do yield x * x] let l3 = [for x in 0..4 do if (x*x) % 2 = 0 then yield x*x]
Doesn’t look that different. I don’t know which one I prefer.