Created
June 10, 2015 02:54
-
-
Save havenwood/e1b65e004ce716f428b0 to your computer and use it in GitHub Desktop.
Imitating Elixir's Stream.unfold/2 in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Enumerator | |
def self.unfold tuple | |
new do |yielder| | |
loop do | |
current, tuple = yield tuple | |
yielder << current | |
end | |
end | |
end | |
end | |
FiveAndDown = Enumerator.unfold 5 do |n| | |
[n, n - 1] | |
end | |
FiveAndDown.first 10 | |
#=> [5, 4, 3, 2, 1, 0, -1, -2, -3, -4] | |
Fibonacci = Enumerator.unfold [0, 1] do |a, b| | |
[a, [b, a + b]] | |
end | |
Fibonacci.first 10 | |
#=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
Author
havenwood
commented
Jun 10, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment