Clojure 中对多个向量求和的惯用方法
问题:我有一个向量或列表的集合,我想找到一种惯用的方法来对可能具有大小不均匀的向量的现有向量求和。 显示设置的人为示例:
=>(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等等。
我尝试过的:我已经以几种不同的方式尝试了 map
和 for
循环,但我似乎遇到了以下问题:延迟排序或尝试将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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,如果lists-to-add包含偶数长度的列表,会容易得多,所以使用
partition
而不是partition-all
:然后你可以这样做使用
map
和递归进行求和:First of all, it'll be much easier if lists-to-add contains lists of even length, so use
partition
instead ofpartition-all
:And then you can do the summing with
map
and recursion: