3 ms·
This doesn't seem to be really utilizing the value of lazy enumerators. If this was correctly using lazy enumerators, it wouldn't require a range to be passed
by gfunk911 14y ago
This doesn't seem to be really utilizing the value of lazy enumerators.
If this was correctly using lazy enumerators, it wouldn't require a range to be passed in, and you would take values from the resulting lazily evaluated enumerators until you found one >= 1000. All the laziness does here is prevent the select from being evaluated until the sum is called.
I don't have 2.0 installed, so this probably has bugs/errors/etc, but I believe this is what he was going for.
module TakeUntil
refine Enumerator::Lazy do
def take_until(&b)
next_obj = take(1).first
if yield(next_obj)
[]
else
[next_obj] + take_until(&b)
end
end
end
end
class FunctionalRuby
using TakeUntil
def sum_of_multiples_under(max)
(1..99999999).lazy.select { |x| (x % 3 == 0) || (x % 5 == 0) }.take_until { |x| x > 1000 }.sum
end
end
FunctionalRuby.new.sum_of_multiples_under(1000)