Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function that accepts a typed array parameter

Tags:

raku

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 ?

like image 214
zentrunix Avatar asked Dec 31 '20 14:12

zentrunix


People also ask

Can we send an array as a parameter to a function?

A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.

How do you declare an array in a function?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

How do you pass an array as a function parameter in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.


1 Answers

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
}
like image 143
user0721090601 Avatar answered Oct 20 '22 12:10

user0721090601