Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

raku - How to declare a function that accepts a typed array parameter

Say I want to declare a function whose parameter is an array of strings:

sub process-string-array(Str[] stringArray) # invalid
{
  ...
}

How would I do that ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It depends on the sigil you want to use:

sub process-string-array(Str        @array) { ... }  # @-sigil
sub process-string-array(Array[Str] $array) { ... }  # $-sigil

Note that you have to be careful to pass in a declared Str array to do this which means adhoc arrays will need to passed in with a typed declaration:

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

If you don't want to deal with typing arrays like this, you can use a where clause to accept any Any-typed array that happens to include only Str elements (which is often easier to use IME):

sub process-string-array(@array where .all ~~?Str) { ... }

This, however, (as jnthn reminds in the comments) requires type checking each element (so O(n) perf versus O(1) ), so depending on how performance sensitive things are, it may be worth the extra code noise. Per Brad's suggestion, you could multi it, to speed things up when the array is typed and fallback to the slower method when not.

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...