• #### Re: map and reduce

From B. Pym@21:1/5 to All on Fri Jul 19 15:48:02 2024
Consider n vectors (or lists) v1, ..., vn of equal length, an n-
variate function f, and a bivariate function g.

I want to calculate (reduce g (map 'vector f v1 v2 ... vn)), eg

(reduce #'+ (map 'vector #'* '(1 2 3) '(4 5 6))) ; => 32

but without the intermediate vector (my vectors are long). I can of
course write a function to do this, but I am wondering if there is a
clever way to do it with CL library functions.

I don't think there is a way to do this sort of thing directly. It's
not difficult (or even particularly ugly) to do using LOOP, though. For
the case G = #'+, it's particularly nice:

(loop for x across first-vector
for y across second-vector
sum (funcall f x y))

That cannot handle any number of vectors.

but for general G, you need

(loop for x across first-vector
for y across second-vector
for temp = (funcall f x y)
for result = temp then (funcall result temp)

Wrong. Try (funcall G result temp)

finally (return result))

Gauche Scheme

(use srfi-43) ;; vector ops.

(define (vec-map-reduce red-func seed map-func . vectors)
(apply vector-fold
(lambda (i accum . elements)
(red-func accum (reduce map-func #f elements)))
seed
vectors))

(vec-map-reduce + 0 *
#(9 2 3 4)
#(5 6 7 8)
#(20 22 23 24))

===>
2415

--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)