TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Lazy Ruby

48 点作者 sonnym大约 11 年前

5 条评论

omaranto大约 11 年前
I think I would write the fibs expression as<p><pre><code> fibs = [true,false].lazy.flat_map{|i| if i then [1,1] else fibs.zip(fibs.drop(1)).map{|a,b| a+b} end} </code></pre> instead of the author&#x27;s<p><pre><code> fibs = inf.map do |n| if n &lt; 3 1 else fibs.zip(fibs.drop(1)).map { |a, b| a + b }.first(n - 2).last end end </code></pre> because I think my way looks a lot closer to the Haskell version. It still has the problem that Enumerator::Lazy doesn&#x27;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大约 11 年前
I 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.<p><a href="http://stackoverflow.com/questions/21790868/simple-aspect-oriented-duck-typing-in-ruby" rel="nofollow">http:&#x2F;&#x2F;stackoverflow.com&#x2F;questions&#x2F;21790868&#x2F;simple-aspect-or...</a>
SeoxyS大约 11 年前
I 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:<p><a href="http://kswizz.com/post/50429268286/fibonacci-the-y-combinator-in-c" rel="nofollow">http:&#x2F;&#x2F;kswizz.com&#x2F;post&#x2F;50429268286&#x2F;fibonacci-the-y-combinato...</a>
mossity大约 11 年前
On a similar theme, I did a blog post a while back on lazy quicksort in Ruby: <a href="http://mossity.com/2013/08/17/implementing-a-lazy-quicksort-with-ruby/" rel="nofollow">http:&#x2F;&#x2F;mossity.com&#x2F;2013&#x2F;08&#x2F;17&#x2F;implementing-a-lazy-quicksort-...</a>
jasdeepsingh大约 11 年前
I wrote the following blog post a while back on a similar note. ;)<p><a href="http://jasdeep.ca/2012/08/easy-memoization-ruby/" rel="nofollow">http:&#x2F;&#x2F;jasdeep.ca&#x2F;2012&#x2F;08&#x2F;easy-memoization-ruby&#x2F;</a>