我必须实现集合并集、差异和交集。然而,当插入带有元组的极其嵌套的集合时,它给了我错误的答案。我已经包含了函数的代码片段。有什么建议可以提高我的输出吗?
val x17 = {1, 2, 8};
val x18 = {{1, 2, 8}, (1, {1, 2, 8})};
val x19 = ({{1, 2, 8}, (1, {1, 2, 8})}, {1, 2, 8});
示例操作:
x20 = {x19} Union x18;
x21 = x20 \ {x17};
x22 = x20 intersection {x17};
正确答案:
x20 ={{1, 2, 8}, (1, {1, 2, 8}), ({{1, 2, 8}, (1, {1, 2, 8})}, {1, 2, 8})};
x21 ={(1, {1, 2, 8}), ({{1, 2, 8}, (1, {1, 2, 8})}, {1, 2, 8})};
x22 ={{1, 2, 8}};
我的输出:
let x20 be {{1,2,8},(1,{1,2,8})};
let x21 be {(1,{1,2,8})};
let x22 be {{1,2,8}};
代码
datatype expression = SET of expression list | INT of int
fun interFunc (SET [],SET b,interSet) = SET (rev interSet)
| interFunc (SET a,SET [],interSet) = SET (rev interSet)
| interFunc (SET (h1::t1),SET b,interSet) = if (List.exists (fn x=>x=h1) b) then interFunc(SET t1,SET b,h1::interSet) else interFunc(SET t1,SET b,interSet);
fun garbage [] = []
| garbage (h::t) = if (List.exists (fn x=>x=h) t) then h::(garbage t) else (garbage t);
fun unionFunc (SET [],SET b) = SET (b)
| unionFunc (SET a,SET []) = SET (a)
| unionFunc (SET a,SET b) = SET (garbage a@b);
(* set operation: difference, modified interFunc *)
fun diffFunc (SET [],SET b,diffSet) = SET (rev diffSet)
| diffFunc (a,SET [],diffSet) = SET (rev diffSet)
| diffFunc (SET (h1::t1),SET b,diffSet) = if (List.exists (fn x=>x=h1) b) then diffFunc(SET t1,SET b,diffSet) else diffFunc(SET t1,SET b,h1::diffSet);