3 ms·
If you're first going to golf it, endless-def: def fib(n, cache=Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }) = cache[n]
by vidarh 2y ago
If you're first going to golf it, endless-def:
def fib(n, cache=Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }) = cache[n]
- jaggederest 2y agoIt's actually kind of ungolfed. The default version would be just fib = Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] } fib[7145]
- inopinatus 2y agoThis is the proper Ruby form since it relies on the [] operator and is therefore substitutable for any other callable esp. procs/lambdas, and able to wrap them as well. This isn’t just golf, it’s an excellent way to pass around a lazily computed, self-caching closure. I use it often in preference to memoization gems. Aside from noting the false/nil equivalence concern, the original article seems over-engineered to me. Excessive metaprogramming is a common trap for Ruby devs.
- nyrikki 2y agoIMHO, the mamul form is even better for golf, F(n) in O(n log n)