4

Here is the Fibonacci code on the Elm syntax page. Just curious does recursion need to be memoized or does lazy evaluation take care of it?

fib n = case n of
  0 -> 1
  1 -> 1
  _ -> fib (n-1) + fib (n-2)

In other languages (such as Python) the number of function calls would grow exponentially in n so that in if f(30) would compute f(10) like 4000 times or someting.

Community
  • 1
  • 1
john mangual
  • 7,718
  • 13
  • 56
  • 95

1 Answers1

5

Viewing the compiled source (as of Elm 0.18), you'll see that the Elm code gets transpiled down to the following javascript code (the variable names may differ).

var _user$project$Temp1483721371847322$fib = function (n) {
    var _p0 = n;
    switch (_p0) {
        case 0:
            return 1;
        case 1:
            return 1;
        default:
            return _user$project$Temp1483721371847322$fib(n - 1) + _user$project$Temp1483721371847322$fib(n - 2);
    }
};

Javascript does no automatic memoization since function calls are not guaranteed to be deterministic. If you require memoization, you will have to roll your own.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97