{-# LANGUAGE RankNTypes #-} -- just to enable "forall" import Prelude hiding (fst, snd, zip, unzip) ------------------------------------------------------------------ -- Union types: data Union a b = This a | That b -- predefined as: -- data Either a b = Left a | Right b mixedList :: [Union Int Bool] mixedList = [This 0, That True, This 42] -- Returns the sum of all integer elements in a mixed list: sumInts :: [Union Int a] -> Int sumInts [] = 0 sumInts (This x : xs) = x + sumInts xs sumInts (That x : xs) = sumInts xs eitherList :: [Either Int Bool] eitherList = [Left 0, Right True, Left 42] ------------------------------------------------------------------ -- Tuple types: --data (,) a b = (,) a b -- pairs --data (,,) a b c = (,,) a b c -- triples aPair :: (Int, String) aPair = (42, "Hello World!") aTriple :: (Int, Bool, Char) aTriple = (42, False, 'A') -- First component of a pair: fst :: (a,b) -> a fst (x,y) = x -- Second component of a pair: snd :: (a,b) -> b snd (x,y) = y -- Combine the elements of two lists pairwise: zip :: [a] -> [b] -> [(a,b)] zip [] _ = [] zip _ [] = [] zip (x:xs) (y:ys) = (x,y) : zip xs ys -- Splits a list of pairs into their elements: unzip :: [(a,b)] -> ([a],[b]) unzip [] = ([],[]) unzip ((x,y):xys) = let (xs,ys) = unzip xys in (x : xs, y : ys)