How does this Haskell function work?

I struggled to understand how this function works. For the nth number, he must calculate the sum of the three previous elements.

f' :: Integer->Integer f' = helper 0 0 1 where helper abc 0 = a helper abcn = helper bc (a+b+c) (n-1) 

thank you for your time

+4
source share
4 answers

they say that he was called using f' 5

below is the sequence in which it will be executed:

Iteration 1: helper 0 0 1 5

iteration 2: helper 0 1 (0 + 0 + 1) 4

iteration 3: auxiliary 1 1 (0 + 1 + 1) 3

iteration 4: auxiliary 1 2 (1 + 1 + 2) 2

iteration 5: auxiliary 2 4 (1 + 2 + 4) 1

iteration 6: auxiliary 4 7 (2 + 4 + 7) 0 => 4

+4
source

Perhaps the part you are missing is that

 f' = helper 0 0 1 

is the same as

 f' x = helper 0 0 1 x 

Otherwise, see Dave's answer.

+7
source

This is a fairly simple recursive function. When called with three elements (I guess the seeds for the sequence) and the number of terms, it calls itself by looping the seed left alone and adding a new term (a + b + c). When the "number of remaining steps" counter reaches 0, the edge is taken and returns the value of the current sequence. This value is passed back to all function calls, giving the final output.

The f' function provides a simple wrapper around the helper function (which does the work described above), providing a standard seed and passing the requested term as the 4th parameter (this explains the mathematical approach).

+5
source

This is similar to the Fibonacci sequence, but for 3 numbers, not 2:

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

where is the Fibonacci sequence

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

Source: https://habr.com/ru/post/1481600/


All Articles