Ruby needs continuations...

  • Thread starter Just Another Victim of the Ambient Morality
  • Start date
M

MonkeeSage

========
require 'generator'
module Enumerable
def izip(*enumerables)
enumerables = [self] + enumerables
generators= enumerables.map { | enum |
Generator.new(enum)
}
whilegenerators[0].next?
result =generators.map { | gen |
gen.next
}
yield result
end
end
end
[1,2,3].izip([4,5,6]) { | x, y |
puts x, y
}
========
NB. generator.rb says thatgeneratorsare slow in 1.8.
Regards,
Jordan
Ps. The SyncEnumerator class from generator does the same thing as
izip:
SyncEnumerator.new([1,2,3], [4,5,6]).each { | x, y |
puts x, y
}

Thank you, MonkeeSage, this is exactly what I'm looking for!
It's interesting thatgeneratorsare slow enough to warn users about its
lack of speed! Do you know if it would be any faster implemented with
continuations? I'm surprised it's so slow considering Ruby employs green
threads...

Just for posterity, it should be noted that in this particular example
(and several others from itertools), you don't even need generators;
internal iterators work just fine...

def izip(*enums)
(enums[0].length).times { | i |
elems = enums.map { | enum |
enum
}
yield elems
}
end

izip([1,2,3], [4,5,6], [7,8,9]) { | elem |
p elem
}

Of course, you have to be wary about gotchas regarding the elements
being iterable and so forth; just thought it was worthy of mention
that this is possible with the built-in iteration construct, without
resorting to external iterators.

Regards,
Jordan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,218
Latest member
JolieDenha

Latest Threads

Top