Programming-Idioms

History of Idiom 31 > diff from v37 to v38

Edit summary for version 38 :
[Ruby] Alternative impl => new impl 1946. No sample values in code.

Version 37

2017-03-19, 20:56:31

Version 38

2017-03-19, 20:58:32

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Code
f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1
f[23] # => 25852016738884976640000

# in one line using tap
fac = Hash.new {|h, i| h[i] = i * h[i-1] }.tap {|h| h[0] = 1 }
fac[23] # => 25852016738884976640000
Code
f = Hash.new { |hash, i| hash[i] = i * hash[i -1] }
f[0] = 1
Comments bubble
Note that f is not a function but plain old Hash used as a cache for performance.
Comments bubble
Note that f is not a function but plain old Hash used as a cache for performance.