简体   繁体   English

在haskell中折叠的拼图功能?

[英]puzzle function with fold in haskell?

I am having a hard time trying to figure out how does this function works, and I need an explanation from an expert. 我很难弄清楚该功能的工作原理,我需要专家的解释。 Appreciate any help! 感谢任何帮助!

puzzle n x = scanr (\y acc -> (acc + y/acc)/2) 1 (replicate n x)

I tried running these: 我尝试运行这些:

--puzzle 10 2

--puzzle 10 5

--puzzle 10 36

and it gives me this output, respectively: 它分别给我这个输出:

[1.414213562373095,1.414213562373095,1.414213562373095,1.414213562373095,1.414213562373095,1.414213562373095,1.4142135623746899,1.4142156862745097,1.4166666666666665,1.5,1.0]

[2.23606797749979,2.23606797749979,2.23606797749979,2.23606797749979,2.23606797749979,2.236067977499978,2.2360688956433634,2.238095238095238,2.3333333333333335,3.0,1.0]

[6.0,6.0,6.0,6.0,6.000000005333189,6.0002529841194185,6.055351744849479,6.872226737643129,10.222972972972974,18.5,1.0]

This function calculates a square root using Newton`s formula and stores all iteration results in list. 该函数使用牛顿公式计算平方根,并将所有迭代结果存储在列表中。

Here is a Newton's method on wiki. 是Wiki上的牛顿法。

Storing process is based on definition of scanr function: 存储过程基于扫描仪功能的定义:

scanr is similar to foldr, but returns a list of successive reduced values from the right scanr与foldr类似,但是从右侧返回一个连续的减小值的列表

It makes a list of n x-es like [x,x,x,x,x,..] (n times) 它列出了n个x-es的列表,例如[x,x,x,x,x,..](n次)

and then what it does is: 然后它的作用是:

x1 = ( 1 +  x/1)/2
x2 = (x1 + x/x1)/2
x3 = (x2 + x/x2)/2
x4 = (x3 + x/x3)/2

and the result is [xn,x(n-1),...,x2,x1] 结果是[xn,x(n-1),...,x2,x1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM