elixir /examples/fibonacci.exs

Language text Lines 0
MD5 Hash 0fa6578f95a0df08507002ba57e54a18
Repository git://github.com/josevalim/elixir.git View Raw File
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
% A tail call optimized fibonacci.
module Math
  def fibonacci(n)
    fibonacci(n, 1, 0)
  end

  def fibonacci(0, _, result)
    result
  end

  def fibonacci(n, next, result)
    fibonacci(n - 1, next + result, next)
  end
end

Math.fibonacci(0)   % => 0
Math.fibonacci(1)   % => 1
Math.fibonacci(3)   % => 2
Math.fibonacci(10)  % => 55
Back to Top