Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement