Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created June 10, 2015 02:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save havenwood/e1b65e004ce716f428b0 to your computer and use it in GitHub Desktop.
Save havenwood/e1b65e004ce716f428b0 to your computer and use it in GitHub Desktop.
Imitating Elixir's Stream.unfold/2 in Ruby
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]
@havenwood
Copy link
Author

# Elixir
defmodule Fib do
  def seq({a, b} \\ {0, 1}) do
    Stream.unfold {a, b}, fn
      {a, b} -> {a, {b, a + b}}
    end
  end 
end

Fib.seq |> Enum.take 5
#=> [0, 1, 1, 2, 3]
Fib.seq({0, -1}) |> Enum.take 5
#=> [0, -1, -1, -2, -3]
# Ruby
module Fib
  def self.seq tuple = [0, 1]
    Enumerator.unfold tuple do |a, b|
      [a, [b, a + b]]
    end
  end
end

Fib.seq.take 5
#=> [0, 1, 1, 2, 3]
Fib.seq([0, -1]).take 5
#=> [0, -1, -1, -2, -3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment