foldr和foldr1 Haskell [英] foldr and foldr1 Haskell

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

问题描述

考虑到这对我来说似乎是一个非常强大的资产,我正在试图深入折叠。然而,你可以帮助我:

  foldr(/)2 [1,2,3]  - (1 / (2 /(3/2))),结果0.75(其中2是基数)
foldr1(/)[2,2,3] - (1 /(2 /(3/2)) ),结果3.00 {其中2是基数)

我认为我严肃地监督褶皱。 Thx

解决方案

一般

  foldr1 op [y1,...,yn,x] 

基本上与

  foldr op x [y1,...,yn] 

只要 n> = 1 。也就是说,在你的特殊情况下

  foldr1(/)[2,2,3] 

会评估为 2 /(2/3)= 3



使用除法运算符,它有点无聊,因为

  foldr1(/ )[y,y,x1,...,xn] 
= y /(y /(foldr1(/)[x1,...,xn]))
= foldr1(/)[ x1,...,xn]

全部 n> = 1 。因此,在你的例子中,它应该返回结果

  foldr1(/)[3] 

code>

当然 3.0 ,它确实评估为 3.0



这里是一个不太简单的例子:

  foldr1(/)[2,3,5,7]  -  evals 0.47619047619047616 

在这里,它给出了与 2 /(3 /(5/7))相同的结果,这又是

  foldr(/)7 [2,3,5] 

我希望它能澄清评估顺序。


I am trying to dive deep in the folds, considering it seems a very powerful asset to me. However, can you help me with this:

foldr  (/) 2 [1,2,3] -- (1/(2/(3/2))), result 0,75 {where 2 is base)
foldr1 (/)   [2,2,3] -- (1/(2/(3/2))), result 3.00 {where 2 is base)

I think I am seriously overseeing an essential difference between the folds. Thx

解决方案

In general

foldr1 op [y1, ..., yn, x]

is essentially the same as

foldr op x [y1, ..., yn]

as long as n >= 1. That is, in your special case

foldr1 (/) [2, 2, 3]

will evaluate to 2/(2/3) = 3.

With the division operator, it's a bit boring, because

foldr1 (/) [y, y, x1, ... , xn]
  = y/(y/(foldr1 (/) [x1, ..., xn]))
  = foldr1 (/) [x1, ..., xn]

for all n >= 1. So, in your example, it should just return the result of

foldr1 (/) [3]

which is of course 3.0, and it does indeed evaluate to 3.0.

Here is less degenerate example:

foldr1 (/) [2, 3, 5, 7] --  evals to 0.47619047619047616

Here, it gives the same result as 2 / (3 / (5 / 7)), which is in turn the same as

foldr (/) 7 [2, 3, 5]

I hope it clarifies the order of evaluation a little bit.

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

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