6 ms·
Lazy Ruby
- mossity 12y agoOn a similar theme, I did a blog post a while back on lazy quicksort in Ruby: http://mossity.com/2013/08/17/implementing-a-lazy-quicksort-with-ruby/ http://mossity.com/2013/08/17/implementing-a-lazy-quicksort-...
- jasdeepsingh 12y agoI wrote the following blog post a while back on a similar note. ;) http://jasdeep.ca/2012/08/easy-memoization-ruby/ http://jasdeep.ca/2012/08/easy-memoization-ruby/
- omaranto 12y agoI think I would write the fibs expression as fibs = [true,false].lazy.flat_map{|i| if i then [1,1] else fibs.zip(fibs.drop(1)).map{|a,b| a+b} end} instead of the author's fibs = inf.map do |n| if n < 3 1 else fibs.zip(fibs.drop(1)).map { |a, b| a + b }.first(n - 2).last end end because I think my way looks a lot closer to the Haskell version. It still has the problem that Enumerator::Lazy doesn't memoize, so finding the nth element of fibs (in either of these two Ruby versions) does an exponential (Fibonacci, in fact) number of additions, unlike the Haskell version that does n-1 additions.
- crb002 12y agoI would memoize with an alias_method wrapper and let it hit a cache_hash before calling the original function. This is a generic pattern that should work for all immutable functions. http://stackoverflow.com/questions/21790868/simple-aspect-oriented-duck-typing-in-ruby http://stackoverflow.com/questions/21790868/simple-aspect-or...
- SeoxyS 12y agoI once contrived a Y-Combinator-backed and memoized implementation of fib() in pure C (with the blocks extension for real closures). It was a mess, but it was pretty cool: http://kswizz.com/post/50429268286/fibonacci-the-y-combinator-in-c http://kswizz.com/post/50429268286/fibonacci-the-y-combinato...