Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Enumerator::Lazy

 Enumerator::Lazy

Presented at SF.rb on August 2, 2016.

Erik Berlin

August 02, 2016
Tweet

More Decks by Erik Berlin

Other Decks in Programming

Transcript

  1. Imperative languages
 do iteration like this: int sum = 0;

    for(i = 1; i < 10; i = i + 1) { sum = sum + i; }
  2. Functional languages
 do iteration like this: rec_sum [] = 0

    rec_sum (x:xs) = x + rec_sum xs rec_sum [1..9]
  3. enum = Enumerator.new do |yielder| n = 0 loop do

    yielder.yield(n) n += 1 end end
  4. fib = Enumerator.new do |yielder| a = b = 1

    loop do yielder.yield(a) a, b = b, a + b end end
  5. module Enumerable def lazy_map(&block) Enumerator.new do |yielder| return to_enum(__method__) unless

    block_given? each do |n| yielder.yield(block.call(n)) end end end end
  6. module Enumerable def lazy_select(&block) Enumerator.new do |yielder| return to_enum(__method__) unless

    block_given? each do |n| yielder.yield(n) if block.call(n) end end end end
  7. lazy_integers = (1..Float::INFINITY).lazy lazy_integers.collect { |x| x ** 2 }.

    select { |x| x.even? }. reject { |x| x < 1000 }. first(5) #=> [1024, 1156, 1296, 1444, 1600]
  8. require "prime" lazy_primes = Prime.lazy lazy_primes.select { |x| (x -

    2).prime? }. collect { |x| [x - 2, x] }. first(5) #=> [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31]]
  9. module Enumerable def repeat_after_first return to_enum(__method__) unless block_given? each.with_index do

    |*val, index| index.zero? ? yield(*val) : 2.times { yield(*val) } end end end
  10. require "prime" lazy_primes = Prime.lazy lazy_primes.repeat_after_first. each_slice(2). select { |x,

    y| x + 2 == y }. first(5) #=> [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31]]