文件夹如何工作? [英] How does foldr work?

查看:30
本文介绍了文件夹如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下 foldr 工作吗?

Can anybody explain how does foldr work?

以这些例子为例:

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. Any suggestions?

推荐答案

foldr 从列表的右端开始,并使用您提供的函数将每个列表条目与累加器值组合起来.结果是累加器在所有列表元素中折叠"后的最终值.它的类型是:

foldr begins at the right-hand end of the list and combines each list entry with the accumulator value using the function you give it. The result is the final value of the accumulator after "folding" in all the list elements. Its type is:

foldr :: (a -> b -> b) -> b -> [a] -> b

从这里你可以看到列表元素(a 类型)是给定函数的第一个参数,并且累加器(b 类型)是第二个.

and from this you can see that the list element (of type a) is the first argument to the given function, and the accumulator (of type b) is the second.

对于你的第一个例子:

Starting accumulator = 54
11 -   54  = -43
10 - (-43) =  53

        ^  Result from the previous line

 ^ Next list item

所以你得到的答案是 53.

So the answer you got was 53.

第二个例子:

Starting accumulator = 54
(6  + 54) / 2 = 30
(10 + 30) / 2 = 20
(4  + 20) / 2 = 12
(12 + 12) / 2 = 12

所以结果是 12.

我想补充一点,这是针对有限列表的.foldr 也可以处理无限列表,但我认为最好先了解有限情况.

I meant to add, that's for finite lists. foldr can also work on infinite lists but it's best to get your head around the finite case first, I think.

这篇关于文件夹如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆