-- -- file: prelude.es -- -- created: 14/11/96 by Andrew Rock. -- -- purpose: File of bindings automatically loaded by entre. -- ------ Lists. -- Length of a list. -- length :: [a] -> Integer length xs = if xs == [] then 0 else 1 + length (tail xs) -- is x an element of list xs -- elem :: a -> [a] -> Bool elem x xs = if xs == [] then False else if x == head xs then True else elem x (tail xs) ------ Higher order functions (handy combinators). -- function composition. -- compose :: (b -> c) -> (a -> b) -> (a -> c) compose f g x = f (g x) -- flip the order of arguments in a function of arity 2 -- flip :: (a -> b -> c) -> b -> a -> c flip f x y = f y x ------ Higher order functions for lists. -- map -- map :: (a -> b) -> [a] -> [b] map f xs = if xs == [] then [] else (f (head xs)) : (map f (tail xs)) -- filter -- filter :: (a -> Bool) -> [a] -> [a] filter f xs = if xs == [] then [] else if f (head xs) then (head xs) : (filter f (tail xs)) else filter f (tail xs) -- foldl -- foldl :: (a -> b -> a) -> a -> [b] -> a foldl f z xs = if xs == [] then z else foldl f (f z (head xs)) (tail xs) -- foldr -- foldr :: (a -> b -> b) -> b -> [a] -> b foldr f z xs = if xs == [] then z else f (head xs) (foldr f z (tail xs))