{- Title: Examples from the first lecture Author: Robin Cockett Date: 14 Jan 2003 Notes: some of these functions are in the standard prelude can you identify them? -} -- Appending a pair of lists appendpair:: ([a],[a]) -> [a] appendpair ([],y) = y appendpair ((x:xs),y) = x:(appendpair (xs,y)) -- Appending two lists the curried form append:: [a] -> [a] -> [a] append [] y = y append (x:xs) y = x:(append xs y) {- NOTE: append is polymorphic this mean we can append lists of anything with this function. Try out the following: append [1,2,3] [4,5,6] append ["abc","def"] ["hij,"klm","nop"] append [[1,2],[3,4,5]],[[6,7],[8],[9,10],[11]] -} -- Reversing a list the naive way nrev:: [a] -> [a] nrev [] = [] nrev (x:xs) = append (nrev xs) [x] -- Reversing a list the fast way rev:: [a] -> [a] rev xs = rev1 xs [] where rev1 [] ys = ys rev1 (x:xs) ys = rev1 xs (x:ys) -- Summing a list of integers (note the Haskell type Integer -- has arbitary precision sumlist:: [Integer] -> Integer sumlist [] = 0 sumlist (x:xs) = x + (sumlist xs) -- Mapping a function over a list maplist:: (a -> b) -> [a] -> [b] maplist f [] = [] maplist f (x:xs) = (f x):(maplist f xs) -- Filtering those elements not satisfying a predicate from a list filterlist p [] = [] filterlist p (x:xs) = if p x then x:(filterlist p xs) else (filterlist p xs)