
Haskell 2d : List comprehensions. . If you’ve ever taken a course in mathematics, you’ve probably run into set comprehensions. They’re normally used for building more specific sets out of general sets. A basic comprehension for a set that contains the first ten even natural numbers is set notation. The part before the pipe is called the output function, x is the variable, N is the input set and x<= 10 is the predicate. That means that the set contains the doubles of all natural numbers that satisfy the predicate.. . If we wanted to write that in Haskell, we could do something like take 10 [2,4..]. But what if we didn’t want doubles of the first 10 natural numbers but some kind of more complex function applied on them? We could use a list comprehension for that. List comprehensions are very similar to set comprehensions. We’ll stick to getting the first 10 even numbers for now. The list comprehension we could use is [x*2 | x <- [1..10]]. x is drawn from [1..10] and for every element in [1..10] (which we have bound to x), we get that element, only doubled. Here’s that comprehension in action.. . ghci> [x*2 | x <- [1..10]] . [2,4,6,8,10,12,14,16,18,20] . As you can see, we get the desired results. Now let’s add a condition (or a predicate) to that comprehension. Predicates go after the binding parts and are separated from them by a comma. Let’s say we want only the elements which, doubled, are greater than or equal to 12.. . ghci> [x*2 | x <- [1..10], x*2 >= 12] . [12,14,16,18,20] . Cool, it works. How about if we wanted all numbers from 50 to 100 whose remainder when divided with the number 7 is 3? Easy.. . ghci> [ x | x <- [50..100], x `mod` 7 == 3] . [52,59,66,73,80,87,94]

Haskell 2d List Comprehensions
Haskell 2d List Comprehensions
List Comprehensions In Haskell
List Comprehensions Visually Explained
Haskell 4 List Comprehension Generating Lists From Intervals