Multi sub on Array of Int vs Array of Array of Int
I would like to have a multi-sub where one is for the Ints array and the other multi sub is for an array of Ints arrays.
This looks like a trick:
multi sub abc(Int @array) { say 10; }
multi sub abc(Array[Int] @array) { say 20; }
But constructing literals that satisfy these constraints is pretty verbose:
abc Array[Int].new([1,2,3]); # -> 10
abc Array[Array[Int]].new([Array[Int].new([1,2,3]), Array[Int].new([2,3,4])]); # -> 20
Ideally, I could just say:
abc [1,2,3]
abc [[1,2,3], [2,3,4]]
Is there a way to build abc
that can ship as shown above without all the explicit type annotations?
Can I be configured multi sub
to send at runtime?
source to share
Instead of a cheap nominal type check, you can do a costly structured check with a proposal where
like
multi sub abc(@array-of-Int where .all ~~ Int) { ... }
or
multi sub abc(@matrix-of-Int where .all ~~ Positional & { .all ~~ Int }) { ... }
If you go the nominal type route, you can also consider array forms, which can be declared even more compactly via anonymous variables.
abc my Int @[2;3] = (1,2,3), (2,3,4);
abc Array[Int].new(:shape(2,3), (1,2,3), (2,3,4));
and check through
multi sub abc(Array[Int] $matrix where .shape == 2) { ... }
source to share