FP101x - week 4 List Comprehensions


Set Comprehensions

> [(x,y) | x <- [1,2,3] , y <- [4,5]]
[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
> [(x,y) | y <- [4,5], x <- [1,2,3] ]
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]

dependant Generators

> [(x,y) | x <- [1..3], y <-[x..3]]
[(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]
concat :: [[a]] -> [a]
concat xss = [x|xs <- xss, x <- xs]

> concat [[1,2,3], [4,5], [6]]
[1,2,3,4,5,6]

Guards

> [ x | x <- [1..10], even x]
[2,4,6,8,10]
factors :: Int -> [Int]
factors n = [ x | x <- [1..n], n ‘mod’ x == 0]

> factor 15
[1,3,5,15]
prime :: Int -> Bool
prime n = factors  == [1,n]

> prime 15
false
> prime 7
truer
primes :: Int -> [Int]
primes n = [x | x <- [2..n], prime x]

> primes 40
[2,3,5,7,11,13,17,19,23,29,31,37]

the Zip Function

zip :: [a] -> [b] -> [(a,b)]

> zip [‘a’,’b’,’c’] [1,2,3,4]
[(‘a’,1),(‘b’,2),(‘c’,3)]
pairs :: [a] -> [(a,a)]
pairs xs = zip xs (tail xs)

> pairs [1,2,3,4]
[(1,2),(2,3),(3,4)]
sorted :: Ord a => [a] -> Bool
sorted xs = and [ x <= y | (x,y) <- pairs xs ]

> sorted [1,2,3,4]
True
> sorted [1,3,2,4]
False
positions :: Ez a => a -> [a] -> [Int]
positions x xs =
     [ i | (x’ ,i) <- zip xs [0..n], x == x’]
      where n = length xs - 1

> positions 0 [1,0,0,1,0,1,1,0]
[1,2,4,7]

String Comprehensions

> length “abcde"
5

>take 3 “abcde"
“abc"

> zip “abc” [1,2,3,4]
[(‘a’,1),(‘b’,2),(‘c’,3)]
lowers :: String -> Int
lowers xs = length [x | x <- xs, isLower x]

> lowers “Haskell"
6