Sunday, October 08, 2006

Mapcar in Ruby

A Ruby version of Lisp's mapcar function:
require 'generator'
# One mapcar to rule all Enumerables.
def mapcar(*enums)
generators = enums.collect {|e| Generator.new(e)}
result = []
while true
begin
params = generators.collect {|g| g.current; g.next}
rescue EOFError
return result
end
result << yield(*params)
end
end
Sample usage:
qSorters = arrays.collect {QSort.new}
threads = mapcar(qSorters, arrays) {|q, a| Thread.new {q.quicksort(a)}}
This creates an Array of Threads that use the objects in qSorters to sort each element of arrays.
Please note that the QSort class is user-defined and omitted here for brevity (and sanity).
The above mapcar is based on recipe 7.9, pages 256-257 of the Ruby Cookbook, specifically the interosculate function.

No comments: