Search code examples
smlsmlnj

Find if Duplicates Exist SML NJ opposite


Regarding to an older question Find if Duplicates Exist SML NJ, if I want the opposite result:

[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

how can I have it with:

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

For example,

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

doesn't work.

Why??? Thanks.


Solution

  • If you would like to obtain the opposite result, just define the function as follows:

    fun non_duplicated xs = not (duplicated xs)
    

    That said, you can push not inwards the body of duplicated function using De Morgan laws:

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

    Then you arrive at the opposite version:

    fun non_duplicated [] = true
      | non_duplicated (x::xs) = 
          (List.forall (fn y => x <> y) xs) andalso (non_duplicated xs)