Question

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 ([])

Was it helpful?

Solution 2

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.)

OTHER TIPS

Not regularly. However, a couple of SML implementations -- in particular, SML/NJ -- support vector literals as a language extension. Those can also be used in patterns:

val v = #[1, 2, 3]
val #[x, y, _] = v

However, vectors are not inductively constructed, so you cannot match head and tail like with lists. You can only match vectors with known and fixed length, like above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top