Tutorial by Examples

Haskell has list comprehensions, which are a lot like set comprehensions in math and similar implementations in imperative languages such as Python and JavaScript. At their most basic, list comprehensions take the following form. [ x | x <- someList ] For example [ x | x <- [1..4] ] -...
However, x in the generator expression is not just variable, but can be any pattern. In cases of pattern mismatch the generated element is skipped over, and processing of the list continues with the next element, thus acting like a filter: [x | Just x <- [Just 1, Nothing, Just 3]] -- [1, 3] ...
Another feature of list comprehensions is guards, which also act as filters. Guards are Boolean expressions and appear on the right side of the bar in a list comprehension. Their most basic use is [x | p x] === if p x then [x] else [] Any variable used in a guard must appear on its left ...
List comprehensions can also draw elements from multiple lists, in which case the result will be the list of every possible combination of the two elements, as if the two lists were processed in the nested fashion. For example, [ (a,b) | a <- [1,2,3], b <- ['a','b'] ] -- [(1,'a'), (1,'b'),...
With Parallel List Comprehensions language extension, [(x,y) | x <- xs | y <- ys] is equivalent to zip xs ys Example: [(x,y) | x <- [1,2,3] | y <- [10,20]] -- [(1,10),(2,20)]
List comprehensions can introduce local bindings for variables to hold some interim values: [(x,y) | x <- [1..4], let y=x*x+1, even y] -- [(1,2),(3,10)] Same effect can be achieved with a trick, [(x,y) | x <- [1..4], y <- [x*x+1], even y] -- [(1,2),(3,10)] The let in list compr...
Any list comprehension can be correspondingly coded with list monad's do notation. [f x | x <- xs] f <$> xs do { x <- xs ; return (f x) } [f x | f <- fs, x <- xs] fs <*> xs do { f <- fs ; x <- xs ; return (f x) } [y | x &...

Page 1 of 1