import Prelude hiding (flip, map, foldr, foldl, filter, sum) import Data.Char (chr, ord) -- Computes the square of a float number: square :: Float -> Float square x = x * x -- Computes the cubic of a float number: cubic :: Float -> Float cubic x = x * x * x -- Computes the derivation of a given function: derive :: (Float -> Float) -> (Float -> Float) derive f = f' where f' x = (f (x + dx) - f x) / dx dx :: Float dx = 0.001 add :: Float -> Float -> Float add x y = x + y --add0 :: (Float -> Float -> Float) add0 :: Float -> Float -> Float add0 = \x y -> x + y --add1 :: Float -> (Float -> Float) add1 :: Float -> Float -> Float add1 x = \y -> x + y -- Exchange the order or arguments in a binary function: flip :: (a -> b -> c) -> (b -> a -> c) flip f = \x y -> f y x flipTake :: [a] -> Int -> [a] flipTake = flip take abc :: Int -> String abc = flip take "abcdefghi" --------------------------------------------------------------------------- -- Higher-order functions as programming patterns -- Increments of all elements in an integer list: incList :: [Int] -> [Int] incList [] = [] incList (x:xs) = (x + 1) : incList xs -- Encodes a string by replacing characters: code :: Char -> Char code c | c == 'Z' = 'A' | c == 'z' = 'a' | otherwise = chr (ord c + 1) codeString :: String -> String codeString [] = [] codeString (c:cs) = code c : codeString cs -- Schema: maps a function on all elements of a list: map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs incList' :: [Int] -> [Int] incList' = map (+1) codeString' = map code -- Sum up all numbers in an integer list: sum :: [Int] -> Int sum [] = 0 sum (x:xs) = x + sum xs -- Compute the checksum of a string: checkSum :: String -> Int checkSum [] = 0 checkSum (c:cs) = ord c + checkSum cs -- Schema: Sum up all numbers in an integer list: 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 s -> ord c + s) 0 -- Schema: filter elements in a list according to a given predicate: filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs -- Maps a list into a set, i.e., remove all duplicate elements in integer list: nub :: [Int] -> [Int] nub [] = [] nub (x:xs) = x : nub (filter (/= x) xs) -- Quicksort: qsort :: [Int] -> [Int] qsort [] = [] qsort (x:xs) = qsort (filter (<=x) xs) ++ [x] ++ qsort (filter (>x) xs)