Last active
August 29, 2015 14:19
-
-
Save porras/e8604cb46c710244a948 to your computer and use it in GitHub Desktop.
Lazy comprehension
This file contains hidden or 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
def comprehend(*enums) | |
cycles = enums.map(&:cycle) | |
Enumerator.new do |comprehended| | |
loop do | |
value = cycles.map(&:peek) | |
value = yield value if block_given? | |
comprehended << value | |
(cycles.length - 1).downto(0) do |index| | |
cycles[index].next | |
break unless cycles[index].peek == enums[index].first | |
raise StopIteration if index == 0 | |
end | |
end | |
end.lazy # requires Ruby > 2.0 | |
end | |
comprehend(1..2, 4..6) { |a, b| puts "Generating #{a},#{b}"; [a, b] }.select { |a, b| (a + b).odd? }.take(2).each {|i| p i} | |
# Generating 1,4 | |
# [1, 4] | |
# Generating 1,5 | |
# Generating 1,6 | |
# [1, 6] | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment