Anonymous user
Anonymous recursion: Difference between revisions
→{{header|Ruby}}: Show 2 different ways to limit the scope of 'f'.
(Marked incorrect: (non-anonymous) function) |
(→{{header|Ruby}}: Show 2 different ways to limit the scope of 'f'.) |
||
Line 153:
=> [:error, :error, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]</lang>
To remove the local variable 'f' from the fib() method, we can
<lang ruby>
# Kernel#catch calls the block and returns the value of the block.
def fib(n)
raise ArgumentError, "fib of negative" if n < 0
# f is undefined here
end
# Change 'f' to a block parameter.
# Notice that f.tap { |f| r } => f
# but f.tap { |f| break r } => r
def fib(n)
raise ArgumentError, "fib of negative" if n < 0
proc { |f, n| n < 2 && n || f[f, n - 1] + f[f, n - 2] }
.tap { |f| break f[f, n] }
# f is undefined here
end</lang>
|