Course map
Haskell // 05

Lists

Read

Building lists

A list holds values of one type: [1, 2, 3] :: [Int]. String is just [Char]. Lists are built from the empty list [] with the : ("cons") operator, which adds one element to the front.

nums :: [Int]
nums = 1 : 2 : 3 : []     -- the same as [1, 2, 3]

main :: IO ()
main = do
  print (length nums)        -- 3
  print (nums ++ [4, 5])     -- [1,2,3,4,5]
  print (head nums)          -- 1
  print (take 2 nums)        -- [1,2]
  print [1 .. 5]             -- [1,2,3,4,5]

Lists never change: nums ++ [4] builds a new list and leaves nums alone. That is true of every value in Haskell.

01 / 05