Haskell Hero
Interaktivní učebnice pro začínající Haskellisty
|
Funkce na seznamech IIItakeWhile
Výraz Definice
takeWhile :: (a -> Bool) -> [a] -> [a] takeWhile _ [] = [] takeWhile p (x:s) = if p x then x : takeWhile p s else [] Příklady
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
Výraz Definice
dropWhile :: (a -> Bool) -> [a] -> [a] dropWhile _ [] = [] dropWhile p (x:s) = if p x then dropWhile p s else (x:s) Příklady
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
Definice
zip :: [a] -> [b] -> [(a,b)] zip [] _ = [] zip _ [] = [] zip (x:s) (y:t) = (x,y) : zip s t Příklady
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
Definice
unzip :: [(a,b)] -> ([a],[b]) unzip [] = ([],[]) unzip ((x,y):s) = (x:t,y:u) where (t,u) = unzip s Příklady
unzip [(1,2),(3,4),(5,6)] ~>* ([1,3,5],[2,4,6]) unzip [(True,'c'),(False,'s')] ~>* ([True,False],"cs") zipWith
Výraz Definice
zipWith _ [] _ = [] zipWith _ _ [] = [] zipWith f (x:s) (y:t) = (f x y) : zipWith f s t Příklady
zipWith (+) [3,5,4] [2,1,5,8] ~>* [3 + 2, 5 + 1, 4 + 5] zipWith (:) "abc" ["def","ghi"] ~>* ["adef","bghi"] Poznámka
Funkci zip = zipWith (,) |