如何通过Clojure的两套迭代以退还其笛卡尔产品?

发布于 2025-01-18 01:32:32 字数 590 浏览 4 评论 0 原文

因此,我接受两个集合并想要迭代它们,以便返回一个包含两个集合的叉积的新集合。

(defn cartesian
  "computes Cartesian product of A and B"

  [A B]
  

  use "set", "for")

我对 Clojure 很陌生,所以我不确定为什么要使用“set”,“for”包含在其中。 但 A 和 B 将是集合。现在我想迭代每一个并返回它们的笛卡尔积。示例:

(cartesian #{1 2} #{3 4 5}) => #{[1 3] [1 4] [1 5] [2 3] [2 4] [2 5]}

但我不确定到达那里的步骤。我已经查看了文档等,但找不到我要找的东西。这个问题的其他答案涉及列表等。但我必须使用 2 套。

我正在查看的 atm 正在使用 doseq[e A] 并在其中 doseq[x B] 然后添加每个向量对 [ex] 到一个新的 Set,然后返回它。但这看起来不像是标准的功能解决方案。我走在正确的轨道上吗?如何将其添加到新集合中?

So I take in two Sets and wanna iterate through them in order to return a new set containing the cross product of the two sets.

(defn cartesian
  "computes Cartesian product of A and B"

  [A B]
  

  use "set", "for")

I'm very new to Clojure so I'm not sure why use "set, "for" is included at all.
But A and B will be Sets. Now I wanna iterate through each one and return the Cartesian product of them. Example:

(cartesian #{1 2} #{3 4 5}) => #{[1 3] [1 4] [1 5] [2 3] [2 4] [2 5]}

I'm not sure on the steps to get there though. I have looked through documentation etc but can't find what I'm looking for. Other answer to this deal with lists etc. But I have to use 2 Sets.

What I'm looking at atm is using doseq[e A] and inside that doseq[x B] then add each vector-pair [e x] to a new Set and then return it. This doesn't seem like a standard functional solution though. Am I on the right track? How do I add it to a new Set?

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

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

发布评论

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

评论(2

神爱温柔 2025-01-25 01:32:32

您可以使用

(defn cartesian [A B]
  (set (for [a A
             b B]
         [a b])))

(cartesian #{1 2} #{3 4 5})
;; => #{[2 3] [2 5] [1 4] [1 3] [1 5] [2 4]}

You can accomplish that using for:

(defn cartesian [A B]
  (set (for [a A
             b B]
         [a b])))

(cartesian #{1 2} #{3 4 5})
;; => #{[2 3] [2 5] [1 4] [1 3] [1 5] [2 4]}
眸中客 2025-01-25 01:32:32

使用来自 cartesian-product “https://github.com/clojure/math.combinatorics”rel="nofollow noreferrer">clojure.math.combinatorics。要获得您想要的确切结果(向量集),请使用 into 使用 map 转换器:

(into #{} (map vec) (clojure.math.combinatorics/cartesian-product #{1 2} #{3 4 5}))
=> #{[2 3] [2 5] [1 4] [1 3] [1 5] [2 4]}

Use cartesian-product from clojure.math.combinatorics. To get exact result you want (set of vectors), use into with map transducer:

(into #{} (map vec) (clojure.math.combinatorics/cartesian-product #{1 2} #{3 4 5}))
=> #{[2 3] [2 5] [1 4] [1 3] [1 5] [2 4]}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文