public
Description: Reia is a Ruby/Python-like language for BEAM, the Erlang VM
Homepage: http://reia-lang.org
Clone URL: git://github.com/tarcieri/reia.git
reia / examples / fibonacci.re
100644 51 lines (45 sloc) 1.238 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Fibonacci numbers example
#
# From the toplevel Reia directory, run: bin/reia examples/fibonacci.re
 
module Fibonacci
  # Simple approach. This example uses pattern matching and recursion,
  # although the tail call cannot be optimized in this case.
  def simple(0)
    0
  end
  def simple(1)
    1
  end
  def simple(n)
    simple(n - 1) + simple(n - 2)
  end
    
  # This example uses an optimized tail call, because the last thing it calls
  # is itself. The compiler optimizes these cases into a "goto" call
  def optimized(n)
    optimized(n, 1, 0)
  end
  def optimized(0, _, result)
    result
  end
  def optimized(n, next, result)
    optimized(n - 1, next + result, next)
  end
    
  # Generate a list of Fibonacci numbers
  def list(n)
    [optimized(i) | i in 0..(n - 1)]
  end
    
  # Optimally generate a list of Fibonacci numbers
  def optimized_list(n)
    optimized_list(n - 1, 1, [0])
  end
  def optimized_list(0, _, result)
    result.reverse()
  end
  def optimized_list(n, next, result)
    optimized_list(n - 1, next + result[0], result.unshift(next))
  end
end
    
n = 42
puts("Fibonacci number #{n}: #{Fibonacci.optimized(n)}")
 
n = 10
puts("First #{n} Fibonacci numbers: #{Fibonacci.optimized_list(n)}")