Skip to content

Instantly share code, notes, and snippets.

@dmwit
Created February 17, 2019 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmwit/6e4af9138bd96729d4b746a127aa21f6 to your computer and use it in GitHub Desktop.
Save dmwit/6e4af9138bd96729d4b746a127aa21f6 to your computer and use it in GitHub Desktop.
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