fold(r)的表现力?

时间:2018-02-25 19:39:42

标签: design-patterns functional-programming higher-order-functions fold

我正在撰写有关折叠的博客文章/论文。大多数情况下,我坚持fold : (a -> b -> b) -> b -> [a] -> b签名,但折叠左边也可以。

我需要的是尽可能多的例子,其中fold用于实现众所周知的常用位,例如:

sum = foldr (+) 0

product = foldr (*) 1

any = foldr (||) False

all = foldr (&&) True

(++ ys) = foldr (:) ys

length = foldr (\_ n -> n + 1) 0

reverse = foldr (\x xs -> xs ++ [x]) []

map f = foldr (\x xs -> f x : xs) []

filter p = foldr (\x xs -> if p x then x : xs else xs) []

concat = foldr (++) []

compose = foldr (.) id

上面的所有示例都是在Haskell中编写和测试的,但我可以接受任何语言,包括OO-one。

提前致谢。

更新

foldl f a xs = foldr (\x k a -> k (f a x)) id xs a

factorial n = foldr (*) 1 [1..n]

0 个答案:

没有答案