简体   繁体   English

Clojure:用于向量加法的可变函数

[英]Clojure: Variadic function for vector addition

I want to write a general function to add vectors: 我想编写一个通用函数来添加向量:

With map I can do the following: 使用地图,我可以执行以下操作:

(vec (map + [1 2] [1 2] [1 2]))
⇒ [3 6]

(vec (map + [1 2 3] [1 2 3] [1 2 3]))
⇒ [3 6 9]

I'd like be able to wrap it up into a function that takes any number of vectors. 我希望能够将其包装成一个可以接受任意数量向量的函数。 Currently I have a version that works using loop & recur: 目前,我有一个使用循环和递归的版本:

(defn add-coords [& args]
  (loop [coords (first args) more (rest args)]
    (if (empty? more)
      (vec coords)
      (recur (map + coords (first more))
             (rest more)))))

(add-coords [1 2] [1 2] [1 2])
⇒ [3 6]

(add-coords [1 2 3] [1 2 3] [1 2 3])
⇒ [3 6 9]

Is there any way to do this in one line? 有什么办法可以做到这一点吗? Something like: 就像是:

(defn add-coords [& args] (vec (map + args)))

apply mapv should help: apply mapv应该可以帮助:

user=> (defn add-coords [& args] 
         (when (seq args) 
           (apply mapv + args)))

in action 在行动

user=> (add-coords [1 2 3] [1 2 3] [1 2 3])
[3 6 9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM