Lists - Haskell

My notes here are not meant to be an introduction or guide to learning functional programming. These posts will assume you have a background in another functional language, or at least understand the concepts. Let’s get to it.

Lists in haskell must be of the same type and are declared with your typical [] literal notation.

List concatenation ++

[0, 1, 2] ++ [3, 4, 5]
>> [0, 1, 2, 3, 4, 5]

[0, 1, 2] ++ [3, 4, 'a']
>> Exception

-- Note strings are just lists of characters
['a'] ++ ['b']
>> "ab"

[0, 1, 2, 3, 4] ++ [5]
>> [0, 1, 2, 3, 4, 5]

Add to head of list :

'H':"ello Haskell"
>>Hello Haskell

0:[1,2,3,4,5]
>>[0,1,2,3,4,5]

Access an item in a list !!

[5..10] !! 3
>>8

"Hello Haskell" !! 4
>>'o'

Now that we’ve got the feel for things..chug these operators:

keyword input output
head head [0,1,2] 0
tail tail [0,1,2] [1,2]
init init [0,1,2] [0, 1]
last last [0,1,2] 2
length length [0,1,2] 3
null null [0,1,2] false
reverse reverse [0,1,2] [2,1,0]
take x take 3 [0,1,2] [0,1,2]
drop x drop 3 [0,1,2] []
maximum maximum [0,1,2] 2
minimum minimum [0,1,2] 0
sum sum [0,1,2] 3
product product [1,2,3] 6

Phew now that that is over… List Comprehensions! They give you the ability to manipulate, filter or what have you, a list/set in order to get a new set.

-- add 1 to x where x is [0..5]
[x+1 | x <- [0..5]]
>>[1,2,3,4,5,6]

ahhh yes that familiar notation from discrete math. I’ve missed you.

-- multi var LC's
[x+y | x <- [0,1,2], y <- [3,4,5]]
>>[3,4,5,4,5,6,5,6,7]
-- just what you'd expect
-- in comes a LC fizzbuzz
[if x `mod` 3 == 0 then "fizz" else if x `mod` 5 == 0 then "buzz" else show x | x <- [1..100]]
-- I had to google how to print a haskell int as a string "show <int>"
-- [if x `mod` 3 == 0 then "fizz" else if x `mod` 5 == 0 then "buzz" else x | x <- [1..100]]
-- throws exception since not all the same type are returning.

That’s it for today. Next time we’ll recurse through lists and I’ll cover this.