-- Define function by pattern matching and recursion. List functions map, fold, filter -- E.g. Sum a list of numbers. sum' :: [Int] -> Int sum' [] = 0 sum' (x:xs) = x + sum' xs -- know how foldr, foldl is defined. foldr' :: (a -> b -> b) -> b -> [a] -> b foldr' f x [] = x foldr' f x (y:ys) = f y (foldr' f x ys) sum'' :: [Int] -> Int sum'' l = foldr' (\ x r -> x + r) 0 l sumHelper :: [Int] -> Int -> Int sumHelper [] n = n sumHelper (x:xs) n = sumHelper xs (x+n) sum''' :: [Int] -> Int sum''' l = sumHelper l 0 myfoldl :: (b -> a -> b) -> b -> [a] -> b myfoldl f x [] = x myfoldl f x (y:ys) = myfoldl f (f x y) ys sum_v4 :: [Int] -> Int sum_v4 l = myfoldl (\ acc y -> acc + y) 0 l -- map, folds are very general concept, they exists -- for all haskell user defined data types. E.g., map, fold for trees. data Tree a = Leaf | Node a (Tree a) (Tree a) deriving (Show) foldTree :: (a -> b -> b -> b) -> b -> Tree a -> b foldTree f x Leaf = x foldTree f x (Node y l r) = f y (foldTree f x l) (foldTree f x r) -- Monad type class. -- 1. Methods of Monad type class. -- 2. do-notation for the monad type class. -- f :: (Monad m) => a -> m b -- f x = do -- y <- m1 x -- m1 :: a -> m c -- r <- m2 -- m2 :: m d -- return (combine y r) -- combine y r :: b -- same thing as m1 x >>= (\ y -> m2 >>= \ r -> return (combine y r)) -- mapH2 f l xs = foldl (\ r x -> ) l xs -- known how to define general monadic functions using do-notation. join' :: (Monad m) => m (m a) -> m a join' c = do -- c >>= (\ x -> x) x <- c x -- c >>= (\ x -> x) -- return x -- m (m a) sequence' :: (Monad m) => [m a] -> m [a] sequence' [] = return [] sequence' (x:xs) = do r <- x rs <- sequence' xs return (r:rs) -- putChar :: Char -> IO () putString :: [Char] -> IO () putString s = do r <- sequence' (map putChar s) return () -- map :: (a -> b) -> [a] -> [b] -- map putChar s :: [IO ()] -- sequence' (map putChar s) :: IO [()] -- 3. Examples of Monad: list, maybe, IO, state.