Programming-Idioms

History of Idiom 31 > diff from v35 to v36

Edit summary for version 36 :
[Ruby] one line alternative using tap

Version 35

2016-11-30, 22:20:50

Version 36

2017-03-19, 19:31: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
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
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.