I am attempting to memoize my implementation of a Pascal’s triangle generator, as a Ruby learning experiment. I have the following working code:
module PascalMemo
@cache = {}
def PascalMemo::get(r,c)
if @cache[[r,c]].nil? then
if c == 0 || c == r then
@cache[[r,c]] = 1
else
@cache[[r,c]] = PascalMemo::get(r - 1, c) + PascalMemo::get(r - 1, c - 1)
end
end
@cache[[r,c]]
end
end
def pascal_memo (r,c)
PascalMemo::get(r,c)
end
Can this be made more concise? Specifically, can I create a globally-scoped function with a local closure more simply than this?
Please note that the above construct does achieve memoization, it is not just a simple recursive method.