如何声明一个接受类型化数组参数的函数
假设我想声明一个函数,其参数是一个字符串数组:
sub process-string-array(Str[] stringArray) # invalid
{
...
}
我该怎么做?
回答
这取决于您要使用的印记:
sub process-string-array(Str @array) { ... } # @-sigil
sub process-string-array(Array[Str] $array) { ... } # $-sigil
请注意,您必须小心传入已声明的 Str 数组以执行此操作,这意味着临时数组需要使用类型化声明传入:
my Str @typed-array = <a b c>;
process-string-array <a b c>; # errors
process-string-array @typed-array; # typed array in
process-string-array Array[Str].new: <a b c>; # adhoc typed array
如果你不想处理这样的输入数组,你可以使用一个where子句来接受任何Any只包含Str元素的-typed 数组(这通常更容易使用 IME):
sub process-string-array(@array where .all ~~ Str) { ... }
然而,这(正如 jnthn 在评论中提醒的那样)需要对每个元素进行类型检查(因此 O(n) perf 与 O(1) ),因此根据性能敏感的事情,可能值得额外的代码噪音。根据 Brad 的建议,您可以multi在键入数组时加快速度,在不键入时回退到较慢的方法。
multi sub process-string-array(Int @array) {
... # actual processing here
}
multi sub process-string-array(@array where .all ~~ Str) {
process-string-array Array[Int].new: @array
}
- Note that checking for a typed array is `O(1)` in the size of the array, but the `where` approach is `O(n)` - that is, you really don't want to do it anywhere performance matters.
- You could use multi subs. `multi process-string-array(@array where .all ~~ Str) { samewith( Array[Str].new: @array )}` `multi process-string-array(Str @array) { ... }`