Tutorial by Examples

emptyList = [] singletonList = [0] -- = 0 : [] listOfNums = [1, 2, 3] -- = 1 : 2 : [3] listOfStrings = ["A", "B", "C"]
listA = [1, 2, 3] listB = [4, 5, 6] listAThenB = listA ++ listB -- [1, 2, 3, 4, 5, 6] (++) xs [] = xs (++) [] ys = ys (++) (x:xs) ys = x : (xs ++ ys)
The type constructor for lists in the Haskell Prelude is []. The type declaration for a list holding values of type Int is written as follows: xs :: [Int] -- or equivalently, but less conveniently, xs :: [] Int Lists in Haskell are homogeneous sequences, which is to say that all elements mus...
To process lists, we can simply pattern match on the constructors of the list type: listSum :: [Int] -> Int listSum [] = 0 listSum (x:xs) = x + listSum xs We can match more values by specifying a more elaborate pattern: sumTwoPer :: [Int] -> Int sumTwoPer [] = 0 sumTwoPer (x1...
Access the nth element of a list (zero-based): list = [1 .. 10] firstElement = list !! 0 -- 1 Note that !! is a partial function, so certain inputs produce errors: list !! (-1) -- *** Exception: Prelude.!!: negative index list !! 1000 -- *** Exception: Prelude.!!: inde...
Creating a list from 1 to 10 is simple using range notation: [1..10] -- [1,2,3,4,5,6,7,8,9,10] To specify a step, add a comma and the next element after the start element: [1,3..10] -- [1,3,5,7,9] Note that Haskell always takes the step as the arithmetic difference between terms, and tha...
head [1..10] -- 1 last [1..20] -- 20 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] length [1 .. 10] -- 10 reverse [1 .. 10] -- [10, 9 .. 1] take 5 [1, 2 .. ] -- [1, 2, 3, 4, 5] drop 5 [1 .. 10] -- [6, 7, 8, 9, 10]...
This is how the left fold is implemented. Notice how the order of the arguments in the step function is flipped compared to foldr (the right fold): foldl :: (b -> a -> b) -> b -> [a] -> b foldl f acc [] = acc foldl f acc (x:xs) = foldl f (f acc x) xs -- = foldl f (acc...
This is how the right fold is implemented: foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) -- = x `f` foldr f z xs The right fold, foldr, associates to the right. That is: foldr (+) 0 [1, 2, 3] -- is equivalen...
Often we wish to convert, or transform the contents of a collection (a list, or something traversable). In Haskell we use map: -- Simple add 1 map (+ 1) [1,2,3] [2,3,4] map odd [1,2,3] [True,False,True] data Gender = Male | Female deriving Show data Person = Person String Gender ...
Given a list: li = [1,2,3,4,5] we can filter a list with a predicate using filter :: (a -> Bool) -> [a] -> [a]: filter (== 1) li -- [1] filter (even) li -- [2,4] filter (odd) li -- [1,3,5] -- Something slightly more complicated comfy i = notTooLarg...
zip takes two lists and returns a list of corresponding pairs: zip [] _ = [] zip _ [] = [] zip (a:as) (b:bs) = (a,b) : zip as bs > zip [1,3,5] [2,4,6] > [(1,2),(3,4),(5,6)] Zipping two lists with a function: zipWith f [] _ = [] zipWith f _ [] =...

Page 1 of 1