Skip to content

Instantly share code, notes, and snippets.

@bew
Created March 27, 2017 02:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bew/9371c08d1389922bc4a8f91d5f29523f to your computer and use it in GitHub Desktop.
Save bew/9371c08d1389922bc4a8f91d5f29523f to your computer and use it in GitHub Desktop.
struct Int
def palindrome?
self.to_s == self.to_s.reverse
end
end
struct LazyIterator(T)
include Iterator(T)
struct Yielder(T)
def initialize(@chan : Channel(T))
end
def <<(value : T)
@chan.send value
end
end
@data_chan = Channel(T).new(1)
@end_chan = Channel(Nil).new
@launched = false
# Create a LazyIterator, and launch data generation
def initialize(&@generator : Yielder(T) ->)
end
# Return the next value from the data generator
def next
return Iterator::Stop::INSTANCE if @end_chan.closed?
unless @launched
launch_data_generation
end
@data_chan.receive
end
# Launch data generation in separate fiber
private def launch_data_generation
data_chan = @data_chan
end_chan = @end_chan
generator = @generator
spawn do
generator.call Yielder(T).new(data_chan)
end_chan.close
end
@launched = true
end
end
# Use the magic :)
nums = LazyIterator(Int32).new do |yielder|
(100..999).each do |i|
(i..999).each do |j|
yielder << i * j
end
end
end
puts nums.select(&.palindrome?).max
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment