4
fun p( x::xl ) =
  if x::xl = [] then []
  else [0];

It received a Warning: match non exhaustive.

x::xl => ...

What I want to do is:

p( [] ) = []

When I do this, it gives a uncaught exception Match [nonexhaustive match failure]

Jam
  • 113
  • 2
  • 7

1 Answers1

6

What you test, x::xl = [], will never be true. Lists are algebraic types and are defined as

datatype 'a list = :: of 'a * 'a list
                 | []

meaning a value that is a list is either the empty list or some element put in front of another list.

So once your initial pattern matching of x::xl has succeeded, you know that it is not empty. (This should be fairly clear, though, since what would it assign to x if x::xl was empty; the first element of the empty list?)

You seem to be mixing two styles here, one being pattern matching and the other being if-then-else.

fun p [] = []
  | p (_::_) = [0]

fun p xs = if List.null xs then [] else [0]
sshine
  • 15,635
  • 1
  • 41
  • 66