Haskell Hero
Haskell Hero es un manual interactivo del lenguaje Haskell para principiantes.
|
Funciones aplicadas a listas IIItakeWhile
La expresión Definición
takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p (x:s) = if p x then x : takeWhile p s else [] Ejemplos
takeWhile (<5) [1,2,6,7,3,4] ~>* [1,2] takeWhile even [2,4,6,5,7,8] ~>* [2,4,6] takeWhile id [False,True,True] ~>* [] dropWhile
La expresión Definición
dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p (x:s) = if p x then dropWhile p s else (x:s) Ejemplos
dropWhile (<5) [1,2,6,7,3,4] ~>* [6,7,3,4] dropWhile even [2,4,6,9,8,7] ~>* [9,8,7] dropWhile id [True, False, False] ~>* [False,False] zip
Definición
zip :: [a] -> [b] -> [(a,b)] zip [] _ = [] zip _ [] = [] zip (x:s) (y:t) = (x,y) : zip s t Ejemplos
zip [1,2,3] [4,5,6] ~>* [(1,4),(2,5),(3,6)] zip "abcde" [True,False] ~>* [('a',True),('b',False)] zip [] ["ab","cd"] ~>* [] unzip
Definición
unzip :: [(a,b)] -> ([a],[b]) unzip [] = ([],[]) unzip ((x,y):s) = (x:t,y:u) where (t,u) = unzip s Ejemplos
unzip [(1,2),(3,4),(5,6)] ~>* ([1,3,5],[2,4,6]) unzip [(True,'c'),(False,'s')] ~>* ([True,False],"cs") zipWith
La expresión Definición
zipWith _ [] _ = [] zipWith _ _ [] = [] zipWith f (x:s) (y:t) = (f x y) : zipWith f s t Ejemplos
zipWith (+) [3,5,4] [2,1,5,8] ~>* [3 + 2, 5 + 1, 4 + 5] zipWith (:) "abc" ["def","ghi"] ~>* ["adef","bghi"] Nota
Cuando ya conocemos la función zip = zipWith (,) |