Clojure 中对多个向量求和的惯用方法

发布于 2025-01-03 15:51:53 字数 544 浏览 7 评论 0原文

问题:我有一个向量或列表的集合,我想找到一种惯用的方法来对可能具有大小不均匀的向量的现有向量求和。 显示设置的人为示例:

=>(def collated-list [2 3 4 5 6 7 8])
=>(def lists-to-add (partition-all 3 collatedlist))
=>(def base-list [1 1 1])

我希望结果将分解的整理列表汇总到 base-list 上,例如,第一项为 1 + 2 + 5 + 8等等。

我尝试过的:我已经以几种不同的方式尝试了 mapfor 循环,但我似乎遇到了以下问题:延迟排序或尝试将Integer 添加到Vector 时出现的问题。

这是我第一次使用 Clojure 进行实验,所以几乎可以肯定我在这里误解了函数迭代。

谢谢

Problem: I've got a collection of vectors or lists which I would like to find an idiomatic way to sum onto an existing vector possibly with uneven sized vectors.
Contrived example showing the setup:

=>(def collated-list [2 3 4 5 6 7 8])
=>(def lists-to-add (partition-all 3 collatedlist))
=>(def base-list [1 1 1])

I'd like the result to sum the broken down collated lists onto the base-list, for example, the first item would be 1 + 2 + 5 + 8 and so on.

What I've tried: I've tried a map and a for loop in couple of different ways but I seem to encounter either problems with Lazy Sequencing or problems of trying to add an Integer to a Vector.

These are my first experiments with Clojure so it's almost certainly me mis-understanding functional iteration here.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尐籹人 2025-01-10 15:51:53

首先,如果lists-to-add包含偶数长度的列表,会容易得多,所以使用partition而不是partition-all

(def lists-to-add (partition 3 3 '(0 0) collated-list))

然后你可以这样做使用 map 和递归进行求和:

(defn sum-lists [base-lists lists-to-add]
    (reduce #(map + %1 %2) base-list lists-to-add))

First of all, it'll be much easier if lists-to-add contains lists of even length, so use partition instead of partition-all:

(def lists-to-add (partition 3 3 '(0 0) collated-list))

And then you can do the summing with map and recursion:

(defn sum-lists [base-lists lists-to-add]
    (reduce #(map + %1 %2) base-list lists-to-add))
酒浓于脸红 2025-01-10 15:51:53
; List of list
(def lst (partition 5 (range 200)))

; Base list
(def base [1 1 1 1 1])

; Sum operation
(apply map (fn [& args] (apply + args) ) base lst)
; List of list
(def lst (partition 5 (range 200)))

; Base list
(def base [1 1 1 1 1])

; Sum operation
(apply map (fn [& args] (apply + args) ) base lst)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文