-- 4. cvičení {- Akumulacni funkce na seznamech -} foldr_my :: (a -> b -> b) -> b -> [a] -> b foldr_my f last [] = last foldr_my f last (x:xs) = x `f` (foldr_my f last xs) foldl_my :: (a -> b -> a) -> a -> [b] -> a foldl_my f accum [] = accum foldl_my f accum (x:xs) = foldl_my f (accum `f` x) xs length_2 :: [a] -> Integer length_2 xs = foldr_my (\y ys_len -> 1 + ys_len) 0 xs length_3 :: [a] -> Integer length_3 xs = foldl_my (\acc _ -> acc + 1) 0 xs foldr1_my :: (a -> a -> a) -> [a] -> a foldr1_my f [] = error "foldr1_my: empty list" foldr1_my f (x:[]) = x foldr1_my f (x:xs) = x `f` foldr1_my f xs foldl1_my :: (a -> a -> a) -> [a] -> a foldl1_my f [] = error "foldl1_my: empty list" foldl1_my f (x:xs) = foldl_my f x xs sum_2 :: [Integer] -> Integer sum_2 xs = foldr (+) 0 xs -- vyzkoušejte si tyto příklady: -- https://www.fi.muni.cz/~xukrop/ib015/excercise_listfold.html {- pomoci akumulačních funkcí: - length, sum, product, minimum, maximum, min-max, - id_list, reverse, map, filter -} {- product :: [Integer] -> Integer minimum, maximum :: [Integer] -> Integer minmax :: [Integer] -> (Integer, Integer) id_list :: [a] -> [a] reverse :: [a] -> [a] -- pomocí foldl map :: (a -> b) -> [a] -> [b] -- pomocí foldr filter :: (a -> Bool) -> [a] -> [a] -- pomocí foldr -} length_1 :: [a] -> Integer length_1 [] = 0 length_1 (x:xs) = 1 + length_1 xs length_my_l :: [a] -> Integer length_my_l xs = foldl_my (\acc x -> acc + 1) 0 xs sum_1 :: [Integer] -> Integer sum_1 [] = 0 sum_1 (x:xs) = x + sum_1 xs -- length_my_l [1,2] ~> foldl_my (\acc x -> acc + 1) 0 [1,2] ~> foldl_my (\acc x -> acc + 1) ( (\acc x -> acc + 1) 0 1) [2] ~> foldl_my (\acc x -> acc + 1) 1 [2] ~> foldl_my (\acc x -> acc + 1) ( (\acc x -> acc + 1) 1 2) [] ~> foldl_my (\acc x -> acc + 1) 2 [] ~> 2 {- pomoci akumulačních funkcí: - length, sum, product, minimum, maximum, min-max, - id_list, reverse, map, filter -} data Teleso = Kvadr Double Double Double -- a,b,c | Valec Double Double -- r,v | Kuzel Double Double -- r,v | Koule Double -- r deriving ( Show ) -- objem, povrch