multi sub on Array of Int vs Array of Array of Int

我是研究僧i 提交于 2019-12-10 09:56:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!