Int 数组与 Int 数组数组的 multi sub [英] multi sub on Array of Int vs Array of Array of Int

查看:31
本文介绍了Int 数组与 Int 数组数组的 multi sub的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 multi sub,其中一个用于 Int 数组,另一个 multi sub 用于 Int 数组.

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.

这似乎可以解决问题:

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]]

有没有办法构建一个 abc ,它可以在没有所有显式类型注释的情况下如上所示进行调度?

Is there a way to build an abc which can dispatch as shown above without all the explicit type annotations?

是否可以将 multi sub 设置为在运行时分派?

Can a multi sub be setup to dispatch at runtime?

推荐答案

代替廉价的名义类型检查,您可以使用 where 子句执行昂贵的结构检查,例如

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

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

并通过

multi sub abc(Array[Int] $matrix where .shape == 2) { ... }

这篇关于Int 数组与 Int 数组数组的 multi sub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆