Search code examples
listvectorsmlsmlnj

Pattern matching vector


Is it possible in SML to pattern match against a vector like you can with a list?

With a list I can simply do this:

fun foo ([]) = 0
  | foo (l::ls) = 1 + foo (ls);

How can I do that for a vector?

I tried fun foo (Vector.fromList([])) = 0 but that gives me this error:

Vector.fromList is not a constructor Found near Vector.fromList ([])


Solution

  • You cannot, no.

    Lists have their value constructors, :: and nil exposed as part of their interface, allowing for pattern matching. Vectors do not.

    This probably stems from the fact, that lists are rather easily implemented using datatypes in-language, while providing constant-time access vectors lends itself more to an in-compiler implementation using native arrays.

    Note, that the reason you cannot pattern-match on Vector.fromList is, that it is not a value constructor, but rather a function. (Unlike :: and nil.)