I’ve been digging into pattern matching more in Haxe. I don’t see anything in the docs or cookbook about matching on arrays with unknown length. Here’s a code example of what I’m trying to achieve:
function getSpecialTail(array: Array<Int>): Array<Int> {
return switch(array) {
case [4, 8, 12, tail ...]:
tail;
case _:
[];
}
}
I’m using the ellipsis to signify some operator to let the compiler know to match on any number of elements left in the array. Is there a way to do that?
According to the manual, there’s no way to do this (“arrays can be matched on fixed length”).
I imagine if Haxe ever gets an OCaml target, you would be able to use that :: operator in pattern matching and also on arrays (case [4, 8, 12] :: tail:).
I’m not generally opposed to supporting this, but there are some aspects that have to be considered. Without a length check, switching on an empty Int array on static targets would match [0, ...] and [0, 0, ...] etc. if we simply access each element of the pattern in the array. This means that we’d need a >= check for each pattern, and that in turn leads to grouping and ordering considerations.
Maybe this would make a good haxe-evolution proposal.