我试图弄清楚这一段时间,但我没有成功。 以下函数(powerset)如何详细进行,以[1,2,3]为例输入参数? 非常感谢您的帮助。
有趣的ps L = foldl(fn(x,tl)=> tl @ map(fn xs => x :: xs)tl)[[]] L;
答案 0 :(得分:1)
要正确使用该功能,您必须假设输入列表中没有重复。
该功能可以理解如下:
[[]]
)的集合。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 *)