【问题标题】:Find if Duplicates Exist SML NJ opposite查找是否存在重复 SML NJ 对面
【发布时间】:2013-02-08 07:13:34
【问题描述】:

关于一个较老的问题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')

没用。

为什么??? 谢谢。

【问题讨论】:

  • 假设 ps 是一个字符串列表

标签: sml smlnj


【解决方案1】:

如果你想得到相反的结果,只需定义如下函数:

fun non_duplicated xs = not (duplicated xs)

也就是说,您可以使用De Morgan lawsnot 推入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)

【讨论】:

    猜你喜欢
    • 2012-04-19
    • 2013-10-12
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2014-07-15
    相关资源
    最近更新 更多