Created
February 17, 2019 23:17
-
-
Save dmwit/6e4af9138bd96729d4b746a127aa21f6 to your computer and use it in GitHub Desktop.
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 Stream | |
def initialize(&more) | |
@sofar = [] | |
@more = more | |
end | |
def [](i) | |
while i >= @sofar.length do | |
@sofar += @more.call(@sofar) | |
end | |
@sofar[i] | |
end | |
def iterator() Iterator.new(self) end | |
end | |
class Iterator | |
def initialize(s) | |
@s = s | |
@i = -1 | |
end | |
def next() | |
@i += 1 | |
@s[@i] | |
end | |
end | |
class Durable | |
def initialize(value, duration) | |
@value = value | |
@duration = duration | |
end | |
attr_reader :value, :duration | |
end | |
# Take a Stream of Durable things, and produce a new Stream by adding up the | |
# durations of neighbors with the same value. | |
def coalesce(sd) | |
iterator = sd.iterator | |
current = iterator.next | |
Stream.new do | |
value = current.value | |
duration = 0 | |
while current.value == value do | |
duration += current.duration | |
current = iterator.next | |
end | |
[Durable.new(value, duration)] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment