返回仅在一个列表中出现的元素列表 - SML

时间:2012-10-17 20:52:52

标签: list sml

如果L1 = [1,2,3,4,5]和L2 [4,5,6,7,8],我想返回[1,2,3,5,7,8]元素仅出现在一个列表中。我已经编写了一个函数,返回两个列表中发生的项目列表。

fun exists x nil = false | exists x (h::t) = (x = h) orelse (exists x t);

fun listAnd _ [] = []
  | listAnd [] _ = []
  | listAnd (x::xs) ys = if exists x ys  then x::(listAnd xs ys) 
else listAnd xs ys

我要找的列表应该由L1 @ L2 - (ListAnd L1 L2)给出。我还发现了删除元素并删除重复项的函数。我多次尝试稍微更改remDup功能,这样它就不会留下多次出现的任何项目的痕迹。无法让它工作。我不确定如何使用和组合所有这些功能以使其工作。

fun delete A nil = nil
| delete A (B::R) = if (A=B) then (delete A R) else (B::(delete A R));

fun remDups nil = nil
| remDups (A::R) = (A::(remDups (delete A R)));

1 个答案:

答案 0 :(得分:0)

如果有diff函数diff xs ys返回xsys中的所有元素,则可以轻松实现listOr函数:

fun listOr xs ys = diff (xs@ys) (listAnd xs ys)

diff函数可以与listAnd类似地编写:

fun diff xs [] = xs
  | diff [] _ = []
  | diff (x::xs) ys = if exists x ys  
                      then diff xs ys 
                      else x::(diff xs ys)