TransWikia.com

How to declare a function that accepts a typed array parameter

Stack Overflow Asked by zentrunix on February 11, 2021

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 ?

One Answer

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
}

Answered by user0721090601 on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP