简体   繁体   English

这个Haskell函数如何工作?

[英]How does this Haskell function work?

I was struggling to see how this function worked. 我很难看到这个功能是如何工作的。 For the nth number it should calculate the sum of the previous three elements. 对于第n个数,它应该计算前三个元素的总和。

f' :: Integer->Integer

f' = helper 0 0 1

 where

   helper a b c 0 = a

   helper a b c n = helper b c (a+b+c) (n-1)

Thanks for your time 谢谢你的时间

Perhaps the part that you're missing is that 也许你缺少的那部分是

f' = helper 0 0 1

is the same thing as 是一样的

f' x = helper 0 0 1 x

Otherwise, see Dave's answer. 否则,请参阅戴夫的回答。

It's a fairly simple recursive function. 这是一个相当简单的递归函数。 When called with three elements (I'm guessing seeds for the sequence) and a number of terms, it calls itself, cycling the seed left by one and adding the new term (a+b+c). 当用三个元素(我猜测序列的种子)和许多术语调用时,它调用自身,将种子循环一个并添加新术语(a + b + c)。 When the "number of steps remaining" counter reaches 0, the edge case kicks in and just returns the current sequence value. 当“剩余步数”计数器达到0时,边缘情况开始并且仅返回当前序列值。 This value is passed back up all the function calls, giving the final output. 该值被传递回所有函数调用,给出最终输出。

The f' function provides a simple wrapper around the helper function (which does the work I described above), providing a standard seed and passing the requested term as the 4th parameter (MathematicalOrchid explains this nicely). f'函数提供了一个围绕helper函数的简单包装(它完成了我上面描述的工作),提供了一个标准种子并将所请求的术语作为第四个参数传递(MathematicalOrchid很好地解释了这一点)。

say its called with f' 5 f' 5说它叫

below is the sequence in which it will get executed: 下面是它将被执行的顺序:

iteration 1: helper 0 0 1 5 迭代1:助手0 0 1 5

iteration 2: helper 0 1 (0+0+1) 4 迭代2:辅助0 1(0 + 0 + 1)4

iteration 3: helper 1 1 (0+1+1) 3 迭代3:帮助器1 1(0 + 1 + 1)3

iteration 4: helper 1 2 (1+1+2) 2 迭代4:助手1 2(1 + 1 + 2)2

iteration 5: helper 2 4 (1+2+4) 1 迭代5:辅助2 4(1 + 2 + 4)1

iteration 6: helper 4 7 (2+4+7) 0 => 4 迭代6:辅助器4 7(2 + 4 + 7)0 => 4

It is like a Fibonacci sequence, but for 3 numbers, not 2: 它就像斐波那契序列,但对于3个数字,而不是2:

F'_n = F'_{n-1} + F'_{n-2} + F'_{n-3}

where Fibonacci sequence is Fibonacci序列在哪里

F_n = F_{n-1} + F_{n-2}

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

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