Search code examples
smlsmlnj

How to check if x value exists in a list


This is my code:

fun exist [] x = false
  | exist l::ls x = x=l orelse exist ls x

And I tried to compile, but I got these errors;

Error: infix operator "::" used without "op" in fun dec

Error: clauses don't all have same number of patterns

Error: data constructor :: used without argument in pattern

Error: types of rules don't agree [tycon mismatch] earlier rule(s): 'Z list * 'Y -> bool this rule: ''X * 'W * 'V * ''X -> bool in rule: (l,_,ls,x) => (x = l) orelse ((exist ls) x)

Which part do I need to fix?


Solution

  • Fortunately this has an easy answer. The following:

    exist l::ls x = x=l orelse exist ls x
    

    Parses as:

    (exist l)::(ls x) = x=l orelse exist ls x
    

    Which doesn't work. You just need to disambiguate this with parentheses.

    fun exist [] x = false
      | exist (l::ls) x = x=l orelse exist ls x
    

    Note also that the x is never used in the first case, so it can be replaced with an underscore. This can more clearly communicate that if the list is empty, the second value doesn't matter, so we don't bother binding a name to it.

    fun exist [] _ = false
      | exist (l::ls) x = x=l orelse exist ls x