Common HOFs
Besides foldr
and dropWhile
, Haskell’s standard library contains a number of useful and frequently used HOF.
Taking instead of dropping
The dropWhile
function has an opposite that takes rather than drops elements from the front of a list:
Prelude
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
As long as the elements satisfy the predicate, they are returned. Yet, as soon as a first element is found that does not satisfy the predicate, no more elements are returned.
For example, by passing isDigit
from the Data.Char
module to takeWhile
, we can take the leading digits of a string:
*Main> takeWhile isDigit...