1

关于一个较旧的问题Find if Duplicates Exist SML NJ,如果我想要相反的结果:

[1,2,2,3,4,5,6] should return false
[1,2,3,4,5,6,7] should return true
[1,2,3,4,5,6,1] should return false

我怎样才能拥有它:

fun duplicated [] = false
| duplicated (x::xs) = (List.exists (fn y => x = y) xs) orelse (duplicated xs)

例如,

fun non_duplicated ps =
case ps of
[] => false
| x::xs' => (List.exists (fn y => x<>y) xs') andalso (non_duplicated xs')

不起作用。

为什么???谢谢。

4

1 回答 1

4

如果您想获得相反的结果,只需将函数定义如下:

fun non_duplicated xs = not (duplicated xs)

也就是说,您可以使用De Morgan 定律not向内推函数体:duplicated

not (a orelse b) <=> (not a) andalso (not b)
not exists equal <=> forall (not equal)
not false <=> true

然后你到达相反的版本:

fun non_duplicated [] = true
  | non_duplicated (x::xs) = 
      (List.forall (fn y => x <> y) xs) andalso (non_duplicated xs)
于 2013-02-07T11:53:13.287 回答