我认为我已经正确地在Clojure中实现了Powerset。
(use '(clojure set))
(defn powerset [input result]
(if (nil? (first input))
(concat result #{})
(set (reduce concat
(for [x input]
(let [set-of-x #{x}
input-no-x (set (remove set-of-x input))
next-result (union result (set (list input set-of-x input-no-x)))]
(powerset input-no-x next-result)))))))当然,我感兴趣的是库函数如何将上面的一行代码变成一行代码,但我也感兴趣的是如何使上面的代码变得更加地道。
(if (nil? (first input))觉得不对。let块复制命令式计算。可以接受吗?->>使下面的行更易读吗?(union result (set (list input set-of-x input-no-x)))recur,因为我得到了“重复必须在尾部位置”编译器错误。编辑删除的(loop)从最初发布的版本。-在我已经开始尝试引入循环/重复(尾递归)之后,我错误地复制了粘贴的代码。如何在这个函数中使用循环/重述?
发布于 2012-06-24 08:06:21
关于您的代码的几个随机注释:
loop绑定之后关闭的paren被错误地放置了。即使在修好它之后我也无法运行。(if (nil (first input)) then else)是更具体的编写(注意当时的分支的倒置) (if (seq input) else then)。input-no-x可以以更简单的方式获得:(let [input-no-x (disj input x)])发布于 2012-12-03 19:10:57
我知道这是个老生常谈的问题,但请看这里的解释,有一种简单得多的方法:
http://www.ecst.csuchico.edu/~amk/foo/csci356/notes/ch1/solutions/recursionSol.html
代码(来自https://gist.github.com/796299 )
(defn powerset [ls]
(if (empty? ls) '(())
(union (powerset (next ls))
(map #(conj % (first ls)) (powerset (next ls))))))https://codereview.stackexchange.com/questions/12979
复制相似问题