I want to implement Lisp's mapcar
in Ruby.
Wishful syntax:
mul = -> (*args) { args.reduce(:*) }
mapcar(mul, [1,2,3], [4,5], [6]) would yield [24, nil, nil].
Here is the solution I could think of:
arrs[0].zip(arrs[1], arrs[2]) => [[1, 4, 6], [2, 5, nil], [3, nil, nil]]
Then I could:
[[1, 4, 6], [2, 5, nil], [3, nil, nil]].map do |e|
e.reduce(&mul) unless e.include?(nil)
end
=> [24, nil, nil]
But I'm stuck on the zip
part. If the input is [[1], [1,2], [1,2,3], [1,2,3,4]]
, the zip
part would need to change to:
arrs[0].zip(arrs[1], arrs[2], arrs[3])
For two input arrays I could write something like this:
def mapcar2(fn, *arrs)
return [] if arrs.empty? or arrs.include? []
arrs[0].zip(arrs[1]).map do |e|
e.reduce(&fn) unless e.include? nil
end.compact
end
But I do not know how go beyond more than two arrays:
def mapcar(fn, *arrs)
# Do not know how to abstract this
# zipped = arrs[0].zip(arrs[1], arrs[2]..., arrs[n-1])
# where n is the size of arrs
zipped.map do |e|
e.reduce(&fn) unless e.include?(nil)
end.compact
end
Does anyone have any advice?