我正在尝试在clojure返回笛卡尔积中编写函数
(my-compute-fn [1 2 3] [4 5 6])
Run Code Online (Sandbox Code Playgroud)
将返回
[[1 4] [1 5] [1 6] [2 4] [2 5] ....]
Run Code Online (Sandbox Code Playgroud)
我的尝试导致了这一点
(defn compute [col1 col2]
(let [totcol2 (count col2)
totcol1 (count col2)]
(map #(vector %1 %2)
(mapcat #(repeat totcol1 %1) col1)
(take (* totcol1 totcol2) (cycle col2)))))
Run Code Online (Sandbox Code Playgroud)
这项工作做得多,但看起来有点笨重.什么是更好,更简洁的实现,涉及clojure.core中更容易获得的函数?
谢谢!
编辑:发现了clojure组合,并没有一个神奇的功能方式来做到这一点.
for 是这项任务的主要候选人:
(for [a [1 2 3]
b [4 5 6]]
[a b])
;; => ([1 4] [1 5] [1 6] [2 4] [2 5] [2 6] [3 4] [3 5] [3 6])
Run Code Online (Sandbox Code Playgroud)
您可以提供for任意数量的seq,它会将给定的符号绑定到与它们关联的seq的每个元素.甚至更酷的东西:when让你例如找到所有那些总和为7的产品:
(for [a [1 2 3]
b [4 5 6]
:when (= (+ a b) 7)]
[a b])
;; => ([1 6] [2 5] [3 4])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |