Here is a Haskell function that takes a number n and returns the nth fibonacci number. (I’ve used the index scheme such that the 0th number is 0, the 1st number is 1, 2nd number is 1, 3rd number is 2, and so on.)
fib :: (Integral a) => a -> a
fib 0 = 0
fib n = fibhelper n 0 1
fibhelper :: (Integral a) => a -> a -> a -> a
fibhelper 1 x y = y
fibhelper n x y = fibhelper (n-1) y (x+y)
Now, suppose that, for the sake of efficiency, I want to bypass Haskell’s lazy evaluation and force the evaluation of the updated arguments (using the $! operator, for instance?) What would be the most elegant/idiomatic way to do this?
You can use bang patterns to do this.
Note also that you’re a bit overzealous with the use of the
Integraltype class. Do you really want the index of the fibonacci series to be the same type as the values? I would suggest that you instead use the signature:Also, if you are looking for performance, the use of
Integralshould be avoided entirely.