Map, filter and fold
map
, filter
and foldr
are three commonly used functions to manipulate a list. map
applys f
on all a
s in a list of a
. filter
just filters the list according to p
. foldr
destructs the list by replacing every :
with a operator/or function.
Here are the definitions.
map' :: forall a b. (a -> b) -> [a] -> [b]
map' f [] = []
map' f [x|xs] = [f x | map' f xs]
> map' (\x -> x +1 ) [1..10]
[2,3,4,5,6,7,8,9,10,11]
filter' :: forall a. (a -> Boolean) -> [a] -> [a]
filter' p [] = []
filter' p [x|xs] = if p x
then [x | filter p xs]
else filter p xs
> filter' (\x -> x > 5) [1..10]
[6,7,8,9,10]
foldl' :: forall a b. (b -> a -> b) -> b -> [a] -> b
foldl' f k [] = k
foldl' f k [x|xs] = foldl' f (f k x) xs
> foldl' (+) 0 [1..10]
55
当前内容版权归 hamler-lang 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 hamler-lang .