Haskell Hero
Haskell Hero es un manual interactivo del lenguaje Haskell para principiantes.
|
foldr, foldlfoldr a foldl
La función foldr f v [x1,x2,...,xn] ~>* f x1 (f x2 (... (f xn v))) Escrito en la notación infija: foldr f v [x1,x2,...,xn] ~>* x1 `f` (x2 `f` (... (xn `f` v)))
La función foldl f v [x1,x2,...,xn] ~>* f (f (... (f v x1) x2) ... ) xn En la notación infija: foldl f v [x1,x2,...,xn] ~>* ((v `f` x1) `f` x2) ... `f` xn Definición
foldr :: (b –> a –> a) –> a –> [b] –> a foldr _ v [] = v foldr f v (x:s) = f x (foldr f v s) foldl :: (a –> b –> a) –> a –> [b] –> a foldl _ v [] = v foldl f v (x:s) = foldl f (f v x) s
Ejemplos
foldr (+) 0 [1..5] ~>* 1 + (2 + (3 + (4 + (5 + 0)))) ~>* 15 foldl (+) 0 [1..5] ~>* ((((0 + 1) + 2) + 3) + 4) + 5 ~>* 15 foldr (^) 1 [2..4] ~>* 2 ^ (3 ^ (4 ^ 1)) ~>* 2417851639229358349412352 foldl (^) 1 [2..4] ~>* ((1 ^ 2) ^ 3) ^ 4 ~>* 1 foldr1 a foldl1
Definición
foldr1 :: (a –> a –> a) –> [a] –> a foldr1 _ [x] = x foldr1 f (x:s) = f x (foldr1 f s) foldl1 :: (a –> a –> a) –> [a] –> a foldl1 f (x:s) = foldl f x s Ejemplos
foldr1 (+) [1..5] ~>* 1 + (2 + (3 + (4 + 5))) foldl1 (+) [1..5] ~>* (((1 + 2) + 3) + 4) + 5 Funciones definidas por medio de foldr o foldland
and :: [Bool] -> Bool and = foldr (&&) True or
or :: [Bool] -> Bool or = foldr (||) False sum
sum :: Num a => [a] -> a sum = foldr (+) 0 product
product :: Num a => [a] -> a product = foldr (*) 1 compose
compose :: [a -> a] -> a -> a compose = foldr (.) id minimum
minimum :: Ord a => [a] –> a minimum = foldl1 min maximum
maximum :: Ord a => [a] –> a maximum = foldl1 max |