问题
I'd like to have a multi sub where one is for an array of Ints and the other multi sub is for an array of array of Ints.
This seems to do the trick:
multi sub abc(Int @array) { say 10; }
multi sub abc(Array[Int] @array) { say 20; }
But, building literals that satisfy those constraints is quite 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'd be able to just say:
abc [1,2,3]
abc [[1,2,3], [2,3,4]]
Is there a way to build an abc
which can dispatch as shown above without all the explicit type annotations?
Can a multi sub
be setup to dispatch at runtime?
回答1:
Instead of a cheap nominal type check, you can perform an expensive structural check with a where
clause, eg
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 route of nominal types, shaped arrays might also be worth considering, 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 checked via
multi sub abc(Array[Int] $matrix where .shape == 2) { ... }
来源:https://stackoverflow.com/questions/45344618/multi-sub-on-array-of-int-vs-array-of-array-of-int