import Prelude hiding ((.), curry, uncurry, const) import Data.Char -- Control structures with h.o. functions: {- x := 1; <-- initialize variable x while x < 1000 <-- predicate over x { x = 2*x } <-- transformation on x -} while :: (a -> Bool) -> (a -> a) -> a -> a while p f x | p x = while p f (f x) | otherwise = x pow1000 :: Int --pow1000 = while (\x -> x < 1000) (\x -> 2*x) 1 pow1000 = while (<1000) (2*) 1 ----------------------------------------------------------------- -- Data structure: Array a (where a is the type of elements) -- Implementation: array as a function from indices to values: type Array a = Int -> a -- Constructors: -- The empty array emptyArray :: Array a emptyArray i = error ("Access to non-initialized element " ++ show i) -- An initialized array initArray :: a -> Array a --initArray i = \_ -> i --initArray i = const i initArray = const -- Set some element at an index position putIndex a i v === a[i] = v putIndex :: Array a -> Int -> a -> Array a putIndex a i v = a' where a' j | j == i = v | otherwise = a j -- Selector: get the element at a position: getIndex a i === a[i] getIndex :: Array a -> Int -> a getIndex a i = a i myArray :: Array Int myArray = putIndex (putIndex emptyArray 1 42) 5 99 myArray0 :: Array Int myArray0 = putIndex (putIndex (initArray 0) 1 42) 5 99 ----------------------------------------------------------------- -- Function composition (.) :: (b -> c) -> (a -> b) -> (a -> c) f . g = \x -> f (g x) -- Sum up the ASCII values of all uppercase letters in a string sumLetters :: String -> Int --sumLetters s = sum (filter (\c -> c>64 && c<91) (map ord s)) sumLetters = sum . filter (\c -> c>64 && c<91) . map ord curry :: ( (a,b) -> c) -> ( a -> b -> c ) --curry f = \x y -> f (x, y) curry f x y = f (x, y) uncurry :: ( a -> b -> c ) -> (a,b) -> c uncurry g (x,y) = g x y -- Scalar product of two vectors scalar :: [Int] -> [Int] -> Int scalar xs ys = sum (map (uncurry (*)) (zip xs ys)) myScalar :: Int myScalar = scalar [1,2,3] [4,5,6] -- A constant function const :: a -> b -> a const x _ = x