Horje

ZIPPING and unzipping lists - Lists - Haskell
Learn
Haskell - Lists - Zipping and unzipping lists
Zipping and Unzipping Lists

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  _      []     = []
zipWith f  (a:as) (b:bs) = f a b : zipWith f as bs

> zipWith (+) [1,3,5] [2,4,6]
> [3,7,11]

Unzipping a list:

unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])

> unzip [(1,2),(3,4),(5,6)]
> ([1,3,5],[2,4,6])

Syntax

  • empty list constructor `[] :: [a]`
  • non-empty list constructor `(:) :: a -> [a] -> [a]`
  • head - returns the first value of a list `head :: [a] -> a`
  • last - returns the last value of a list `last :: [a] -> a`
  • tail - returns a list without the first item `tail :: [a] -> [a]`
  • init - returns a list without the last item `init :: [a] -> [a]`
  • xs !! i - return the element at an index i in list xs `(!!) :: Int -> [a] -> a`
  • take n xs - return new list containing n first elements of the list xs `take :: Int -> [a] -> [a]`
  • map :: (a -> b) -> [a] -> [b]
  • filter :: (a -> Bool) -> [a] -> [a]
  • (++) :: [a] -> [a]
  • 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.
    Read Article
    https://develop.horje.com/learn/1434/reference