Haskell LanguageLists


Syntax

  1. empty list constructor

    [] :: [a]

  2. non-empty list constructor

    (:) :: a -> [a] -> [a]

  3. head - returns the first value of a list

    head :: [a] -> a

  4. last - returns the last value of a list

    last :: [a] -> a

  5. tail - returns a list without the first item

    tail :: [a] -> [a]

  6. init - returns a list without the last item

    init :: [a] -> [a]

  7. xs !! i - return the element at an index i in list xs

    (!!) :: Int -> [a] -> a

  8. take n xs - return new list containing n first elements of the list xs

    take :: Int -> [a] -> [a]

  9. map :: (a -> b) -> [a] -> [b]

  10. filter :: (a -> Bool) -> [a] -> [a]

  11. (++) :: [a] -> [a]

  12. concat :: [[a]] -> [a]

Remarks

  1. The type [a] is equivalent to [] a.
  2. [] constructs the empty list.
  3. [] in a function definition LHS, e.g. f [] = ..., is the empty list pattern.
  4. x:xs constructs a list where an element x is prepended to the list xs
  5. f (x:xs) = ... is a pattern match for a non-empty list where x is the head and xs is the tail.
  6. f (a:b:cs) = ... and f (a:(b:cs)) = ... are the same. They are a pattern match for a list of at least two elements where the first element is a, the second element is b, and the rest of the list is cs.
  7. f ((a:as):bs) = ... is NOT the same as f (a:(as:bs)) = .... The former is a pattern match for a non-empty list of lists, where a is the head of the head, as is the tail of the head, and bs is the tail.
  8. f (x:[]) = ... and f [x] = ... are the same. They are a pattern match for a list of exactly one element.
  9. f (a:b:[]) = ... and f [a,b] = ... are the same. They are a pattern match for a list of exactly two elements.
  10. f [a:b] = ... is a pattern match for a list of exactly one element where the element is also a list. a is the head of the element and b is the tail of the element.
  11. [a,b,c] is the same as (a:b:c:[]). Standard list notation is just syntactic sugar for the (:) and [] constructors.
  12. You can use all@(x:y:ys) in order to refer to the whole list as all (or any other name you choose) instead of repeating (x:y:ys) again.