1

我必须实现集合并集、差异和交集。然而,当插入带有元组的极其嵌套的集合时,它给了我错误的答案。我已经包含了函数的代码片段。有什么建议可以提高我的输出吗?

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);
4

1 回答 1

2

副手,我看到了一些错误:


garbage (h::t) = if (List.exists (fn x=>x=h) t) then h::(garbage t) else (garbage t)

看起来garbage是为了通过选择每个值的最后一次出现来删除重复项;例如,给定[1,2,3,2,1,2],它应该返回[3,1,2]。但是,它实际上所做的是丢弃每个值的最后一次出现,因此它会给出[1,2,2]


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);

如果h1发生在b,那么你需要做一些事情来过滤掉它b。上面没有这样做,所以本质上它产生了联合而不是对称差异。


总的来说,我建议阅读 Eric Lippert 的博客文章“如何调试小型程序”,以获取有关调试程序的一般建议。

于 2016-02-27T21:38:26.730 回答