我试图解决这个问题一段时间,但我没有成功。以 [1,2,3] 的示例输入参数为例,以下函数 (powerset) 是如何详细进行的?非常感谢您的帮助。
fun ps L = foldl (fn (x,tl) => tl @ map (fn xs => x::xs) tl) [[]] L;
要正确使用该函数,您必须假设输入列表中没有重复。
函数可以理解如下:
[[]]
) 组成的集合。x
添加到它们中,并将这些结果添加到累加器中。n
元素集,即powerset。为了方便表达痕迹,让我们创建一个辅助函数f
fun f (x, tl) = tl @ map (fn xs => x::xs) tl
现在我们有一个跟踪[1, 2, 3]
:
ps [1, 2, 3]
~> foldl f [[]] [1, 2, 3] (* Step 1 *)
~> foldl f (f (1, [[]])) [2, 3]
~> foldl f ([[]] @ map (fn xs => 1::xs) [[]]) [2, 3]
~> foldl f [[], [1]] [2, 3] (* Step 2 *)
~> foldl f (f (2, [[], [1]])) [3]
~> foldl f ([[], [1]] @ map (fn xs => 2::xs) [[], [1]]) [3]
~> foldl f [[], [1], [2], [2, 1]] [3] (* Step 3 *)
~> foldl f (f (3, [[], [1], [2], [2, 1]])) []
~> foldl f ([[], [1], [2], [2, 1]] @ map (fn xs => 3::xs) [[], [1], [2], [2, 1]]) []
~> foldl f [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]] [] (* Step 4 *)
~> [[], [1], [2], [2, 1], [3], [3, 1], [3, 2], [3, 2, 1]] (* Final result *)