Re: map and reduce

Liste des GroupesRevenir à cl lisp 
Sujet : Re: map and reduce
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lisp
Date : 19. Jul 2024, 17:48:02
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v7e1rf$321ib$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
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
 


Date Sujet#  Auteur
19 Jul 24 o Re: map and reduce1B. Pym

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal