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

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

问题描述

任何人都可以解释 foldr 工作?



以下示例:

 前奏> foldr( - )54 [10,11] 
53
Prelude> foldr(\xy - >(x + y)/ 2)54 [12,4,10,6]
12.0

我对这些执行感到困惑。任何建议?

解决方案

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

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

由此可以看到,列表元素(类型为 a )是给定函数的第一个参数,并且累加器(类型 b )是第二个。



第一个例子:

 开始累加器= 54 
11 - 54 = -43
10 - (-43)= 53

^上一行的结果

^下一个列表项目

所以,你得到的答案是53. 第二个例子:


$ b

 开始累加器= 54 
(6 + 54)/ 2 = 30
(10 + 30)/ 2 = 20
(4 + 20)/ 2 = 12
(12 + 12)/ 2 = 12



所以结果是12.



编辑:我想补充一点,那就是有限清单。 foldr 也可以在无限列表上工作,但我认为最好让您的头部绕过有限的情况。


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

解决方案

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

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.

For your first example:

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

        ^  Result from the previous line

 ^ Next list item

So the answer you got was 53.

The second example:

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

So the result is 12.

Edit: 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.

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

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