我知道有多种方法可以使用 Clojure 解决排列问题。我曾尝试使用 Core.Logic 创建 DCG(定句语法),但库的 DCG 部分过于实验性且无法正常工作。
在下面的代码中,我尝试了两种不同的方法。一个是列表理解(注释掉),类似于我在 Haskell 中解决这个问题的方式。
第二种方法使用 MapCat 将 cons/first 应用于递归调用排列的每个返回值。删除项目确保我不会在每个位置多次使用相同的字母。
有人可以解释一下列表理解方法有什么问题以及 MapCat 方法有什么问题吗?在 Haskell 中推理这类问题要容易得多——我是否缺少关于 Clojure 的一些观点?
(defn remove-item [xs]
(remove #{(first xs)} xs )
)
(defn permutation [xs]
(if (= (count xs) 1)
xs
;(for [x xs y (permutation (remove-item xs))
; :let [z (map concat y)]]
; z)
(mapcat #(map cons first (permutation (remove-item %)) ) xs)
)
)
编辑:@thumbnail 已经解决了评论中的 MapCat 子问题