Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Haskell function work?

Tags:

haskell

I was struggling to see how this function worked. For the nth number it should calculate the sum of the previous three elements.

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

like image 881
A Paul Avatar asked Dec 02 '22 19:12

A Paul


2 Answers

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.

like image 69
MathematicalOrchid Avatar answered Dec 19 '22 17:12

MathematicalOrchid


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). When the "number of steps remaining" counter reaches 0, the edge case kicks in and just returns the current sequence value. 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).

like image 31
Dave Avatar answered Dec 19 '22 19:12

Dave