1

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

1 回答 1

0

如果有一个diff函数返回 in而不是 in 的diff xs ys所有元素,则可以轻松实现该函数:xsyslistOr

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)
于 2012-10-17T21:59:52.490 回答