import SimplePrelude hiding (map, foldr, filter, foldl, sum) -- Increments all numbers in a list. incList :: [Int] -> [Int] incList [] = [] incList (x:xs) = (x+1) : incList xs -- Computes the square of all numbers in a list. sqList :: [Int] -> [Int] sqList [] = [] sqList (x:xs) = (x*x) : sqList xs -- Encodes a string as an unreadable string. codeList :: String -> String codeList [] = [] codeList (c:cs) = (code c) : codeList cs code :: Char -> Char code c | ord c == ord 'z' = 'a' | ord c == ord 'Z' = 'A' | otherwise = chr (ord c + 1) -- Generalization: apply some function to each element of a list: map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = (f x) : map f xs incList' = map (+1) sqList' = map (\x -> x*x) codeList' = map code --------------------------------------------------------------- -- Sums up all elements of a list of numbers. sum :: [Int] -> Int sum [] = 0 sum (x:xs) = x + sum xs -- Check sum function for a string: add all ASCII values of a string checkSum :: String -> Int checkSum [] = 1 checkSum (c:cs) = ord c + checkSum cs foldr :: (a -> b -> b) -> b -> [a] -> b foldr f e [] = e foldr f e (x:xs) = f x (foldr f e xs) sum' = foldr (+) 0 checkSum' = foldr (\c result -> ord c + result) 1 -- Accumulator: sum of the first part of the list sumAcc :: [Int] -> Int sumAcc = addTo 0 where addTo s [] = s addTo s (x:xs) = addTo (s + x) xs foldl :: (b -> a -> b) -> b -> [a] -> b foldl f e [] = e foldl f e (x:xs) = foldl f (f e x) xs sumA = foldl (+) 0 checkSumA = foldl (\result c -> ord c + result) 1 --------------------------------------------------------------- -- Filter all elements in a list satisfying some predicate: filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs -- Delete all duplicates in a list nub :: [Int] -> [Int] nub [] = [] nub (x:xs) = x : nub (filter (/=x) xs) -- Quicksort on a list of numbers. qsort :: [Int] -> [Int] qsort [] = [] qsort (x:xs) = qsort (filter (<=x) xs) ++ [x] ++ qsort (filter (>x) xs) -- Define filter with foldr: filterF :: (a -> Bool) -> [a] -> [a] filterF p = foldr (\x ys -> if p x then x:ys else ys) [] -- Control structure: while while :: (a -> Bool) -> (a -> a) -> a -> a while p f x | p x = while p f (f x) | otherwise = x