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 introduceuse a second block. Nowto limit the scope of 'f', isor onlychange a'f' parameterto ofa bothblock blocksparameter.
 
<lang ruby>def# fib(n)Limit the scope of 'f' to a block.
# Kernel#catch calls the block and returns the value of the block.
def fib(n)
raise ArgumentError, "fib of negative" if n < 0
(proccatch { |(f| f[f,= n] })[proc { |f, n| n < 2 && n || f[f, n - 1] + f[f, n - 2] })[n] }
# 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>
Anonymous user