在 Clojure 中迭代集合的所有对的惯用方法
给定一个集合,我想迭代集合中的所有对。示例
(all-pairs seq)
(all-pairs '(a b c d)) => ([a b] [a c] [a d] [b c] [b d] [c d]))
这是我的想法
(defn all-pairs [coll]
(for [ [idx elmt] (indexed coll)
other-elmt (subvec coll (inc idx))]
(vector elmt other-elm)))
,但感觉不惯用
Given a collection I want to iterate through all pairs in a collection. Example
(all-pairs seq)
(all-pairs '(a b c d)) => ([a b] [a c] [a d] [b c] [b d] [c d]))
Here is my idea
(defn all-pairs [coll]
(for [ [idx elmt] (indexed coll)
other-elmt (subvec coll (inc idx))]
(vector elmt other-elm)))
But it doesn't feel idiomatic
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
怎么样:
How about:
比较懒,而且速度比较快。
(所有对 [1 2 3 4])
<代码>;; => ([1 2] [1 3] [1 4] [2 3] [2 4] [3 4])
(所有对 '(abcd))
<代码>;; => ([ab] [ac] [ad] [bc] [bd] [cd])
Lazy, and relatively fast.
(all-pairs [1 2 3 4])
;; => ([1 2] [1 3] [1 4] [2 3] [2 4] [3 4])
(all-pairs '(a b c d))
;; => ([a b] [a c] [a d] [b c] [b d] [c d])
我可以建议:
编辑:显然我误读了这个问题;由于您只需要不同的不重复对,因此如果您调用此函数的任何域上存在自然排序,我们仍然可以使用此方法。
编辑2
另外:
May I suggest:
EDIT: Clearly I misread the question; since you only want distinct unduplicated pairs, we can still use this approach if a natural ordering exists on whatever domain you're calling this function on.
EDIT 2
Also:
如果您想以“学术风格”编写自己的
组合
函数,您可以尝试然后将其应用到您的问题中,如下所示
If you want to write your own
combinations
function in "academic style," you can tryand then apply it to your problem as follows
一个简单的递归版本应该可以完成您想要的操作:
A simple recursive version that should do what you want:
不是最快的解决方案,但是:
Not the fastest solution, but:
这个怎么样?
或者,如果您寻求惰性序列:
How about this?
Or, if you seek a lazy seq:
这又如何呢?
What about this?
只是另一种可能的解决方案:
Just another possible solution: