Lazy fibonacci in Ruby

泄露秘密 提交于 2019-12-08 00:08:55

问题


I can write a lazy fibonacci in Clojure like this:

(def fib (lazy-cat [1 1] (map +' fib (rest fib))))

and I'm trying (unsuccessfully) to write it in Ruby like this:

fib = Enumerator.new do |yielder|
  yielder << 1 << 1
  fib.zip(fib.drop(1)).map do |a,b|
    yielder << (a + b)
  end
end

In the simplified case, this works:

fib = Enumerator.new do |yielder|
  yielder << 1 << 1
  puts "here"
end
puts fib.take(2).inspect
puts fib.drop(1).take(1).inspect

but this doesn't:

fib = Enumerator.new do |yielder|
  yielder << 1 << 1
  puts "here"
  fib.drop(1)
end
puts fib.take(2).inspect
puts fib.drop(1).take(1).inspect

Why does that last example give me a SystemStackError: stack level too deep error?


回答1:


First, fib in the ruby version is not equivalent to the clojure version. In clojure version, it's a function.

And Enumerable#zip, Enumerable#drop and Enumerable.take are not lazy unless you explicitly specify it. If you don't call Enumerable#lazy, they return an Array (eagerly consuming all items; cause the exception).

def fib
  Enumerator.new do |yielder|
    yielder << 1 << 1
    fib.lazy.zip(fib.lazy.drop(1)).each do |a,b|
      yielder << a + b
    end
  end
end

fib.take(2)
# => [1, 1]
fib.lazy.drop(1).take(1).to_a  # Note: `lazy`, `to_a`.
# => [1]
fib.take(4)
# => [1, 1, 2, 3]


来源:https://stackoverflow.com/questions/26173159/lazy-fibonacci-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!