English 中文(简体)
上级职能的实际例子有多倍多?
原标题:What are practical examples of the higher-order functions foldl and foldr?

The typical academic example is to sum a list. Are there real world examples of the use of fold that will shed light on its utility ?

最佳回答

<条码>倍也许是顺序上最基本的操作。 寻求其效用,就象要求使用一种必要语言的<条码>。

Given a list (or array, or tree, or ..), a starting value, and a function, the fold operator reduces the list to a single result. It is also the natural catamorphism (destructor) for lists.

Any operations that take a list as input, and produce an output after inspecting the elements of the list can be encoded as folds. E.g.

sum      = fold (+) 0

length   = fold (λx n → 1 + n) 0

reverse  = fold (λx xs → xs ++ [x]) []

map f    = fold (λx ys → f x : ys) []

filter p = fold (λx xs → if p x then x : xs else xs) []

组合操作者并不具体列出清单,但可以统一归纳为“常规”数据类型。

因此,作为各种数据类型的最基本业务之一,它当然会有一些用途。 能够承认何时算法可以被描述为一重,是一种有用的技能,可形成更清洁的法典。


参考资料:

问题回答




相关问题
F# under SharpDevelop

Ok this is rather frustrating, I;ve installed the latest version of SharpDevelop, and also installed the F# compiler (as per the link from SharpDevelops website) I am running in Vista. thus far, ...

Functional programming, Scala map and fold left [closed]

What are some good tutorials on fold left? Original question, restored from deletion to provide context for other answers: I am trying to implement a method for finding the boudning box of rectangle,...

Code folding is not saved in my vimrc

I added the following code to my .vimrc: " save and restore folds when a file is closed and re-opened autocmd BufWinLeave *.* mkview autocmd BufWinEnter *.* silent loadview HTML and CSS documents ...

How does foldr work?

Can anybody explain how does foldr work? Take these examples: Prelude> foldr (-) 54 [10, 11] 53 Prelude> foldr (x y -> (x+y)/2) 54 [12, 4, 10, 6] 12.0 I am confused about these executions....

热门标签