-
-
Save bew/9371c08d1389922bc4a8f91d5f29523f to your computer and use it in GitHub Desktop.
This file contains 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
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