-
-
Save norbajunior/117ae443f948633cd8dc2b7ca8b6ee72 to your computer and use it in GitHub Desktop.
Imitating Elixir's Stream.unfold/2 in Ruby
This file contains 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment