top | item 7552685

Lazy Ruby

48 points| sonnym | 12 years ago |sonnym.github.io

5 comments

order
[+] omaranto|12 years ago|reply
I 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.