import SimplePrelude ---------------------------------------------------------------------------- -- Control structures as higher-order functions: -- while loop while :: (a -> Bool) -> (a -> a) -> a -> a while p f x | p x = while p f (f x) | otherwise = x potGT1000 = while (<1000) (*2) 1 ---------------------------------------------------------------------------- -- Data structures implemented by higher-order functions: -- Type of arrays: type Array a = (Int -> a) -- The empty array does not contain an element. emptyArray :: Array a emptyArray = \i -> error "Access to uninitalized element" -- Get an element under an index. getIndex :: Array a -> Int -> a getIndex a i = a i -- Add or set an element at some index position putIndex :: Array a -> Int -> a -> Array a putIndex a i v = \j -> if j==i then v else a j -- An array with a default value: initArray :: a -> Array a initArray v = \i -> v -- An array with elements at positions 1 and 2: a12 = putIndex (putIndex (initArray "") 1 "Hello") 2 "World" ----------------------------------------------------------------------------