How do I implement Common Lisp's mapcar in Ruby? -


i want implement lisp's mapcar in ruby.

wishful syntax:

mul = -> (*args) { args.reduce(:*) }  mapcar(mul, [1,2,3], [4,5], [6]) yield [24, nil, nil]. 

here solution think of:

arrs[0].zip(arrs[1], arrs[2]) => [[1, 4, 6], [2, 5, nil], [3, nil, nil]] 

then could:

[[1, 4, 6], [2, 5, nil], [3, nil, nil]].map |e|    e.reduce(&mul) unless e.include?(nil) end  => [24, nil, nil] 

but i'm stuck on zip part. if input [[1], [1,2], [1,2,3], [1,2,3,4]], zip part need change to:

arrs[0].zip(arrs[1], arrs[2], arrs[3]) 

for 2 input arrays write this:

def mapcar2(fn, *arrs)   return [] if arrs.empty? or arrs.include? []   arrs[0].zip(arrs[1]).map |e|     e.reduce(&fn) unless e.include? nil   end.compact end 

but not know how go beyond more 2 arrays:

def mapcar(fn, *arrs)   # not know how abstract   # zipped = arrs[0].zip(arrs[1], arrs[2]..., arrs[n-1])   # n size of arrs   zipped.map |e|      e.reduce(&fn) unless e.include?(nil)   end.compact end 

does have advice?

if got question need:

arrs = [[1,2], [3,4], [5,6]] zipped = arrs[0].zip(*arrs[1..-1]) # => [[1, 3, 5], [2, 4, 6]]  

or nicer alternative, ihmo:

zipped = arrs.first.zip(*arrs.drop(1)) 

if arrays inside arrs of same length can use transpose method:

arrs = [[1,2], [3,4], [5,6]] arrs.transpose # => [[1, 3, 5], [2, 4, 6]]  

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -