Advertisement
Guest User

how to idioms

a guest
Feb 17th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.85 KB | None | 0 0
  1. class Stream
  2.     def initialize(&more)
  3.         @sofar = []
  4.         @more = more
  5.     end
  6.  
  7.     def [](i)
  8.         while i >= @sofar.length do
  9.             @sofar += @more.call(@sofar)
  10.         end
  11.         @sofar[i]
  12.     end
  13.  
  14.     def iterator() Iterator.new(self) end
  15. end
  16.  
  17. class Iterator
  18.     def initialize(s)
  19.         @s = s
  20.         @i = -1
  21.     end
  22.  
  23.     def next()
  24.         @i += 1
  25.         @s[@i]
  26.     end
  27. end
  28.  
  29. class Durable
  30.     def initialize(value, duration)
  31.         @value = value
  32.         @duration = duration
  33.     end
  34.  
  35.     attr_reader :value, :duration
  36. end
  37.  
  38. # Take a Stream of Durable things, and produce a new Stream by adding up the
  39. # durations of neighbors with the same value.
  40. def coalesce(sd)
  41.     iterator = sd.iterator
  42.     current = iterator.next
  43.     Stream.new do
  44.         value = current.value
  45.         duration = 0
  46.         while current.value == value do
  47.             duration += current.duration
  48.             current = iterator.next
  49.         end
  50.         [Durable.new(value, duration)]
  51.     end
  52. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement