I want to restrict the return type of some of my functions in Perl6. I know, how to deduce the right return type of a function, returning a scalar or an array in Perl6, but I don't know, how I can do this, if I use a hash of a particular type as return value?
Example: The Array approach can be seen in test_arr()
and the Hash approach can be seen in test_hash()
. So I want to specify the return value of test_hash()
, to return a hash of class A.
#!/usr/bin/env perl6
use v6.c;
use fatal;
class A {
has Str $.member;
}
sub test_arr() returns Array[A] {
my A @ret;
@ret.push(A.new(member=>'aaa'));
return @ret;
}
sub test_hash() { #TODO: add `returns FANCY_TYPE`
my A %ret;
%ret.append("elem",A.new(member=>'aaa'));
%ret.append("b",A.new(member=>'d'));
return %ret;
}
sub MAIN() returns UInt:D {
say test_arr().perl;
say test_hash().perl;
return 0;
}
It's really the same as with arrays:
sub test_hash() returns Hash[A] {
my A %ret;
%ret.append("elem",A.new(member=>'aaa'));
%ret.append("b",A.new(member=>'d'));
return %ret;
}
Note that you can also write %ret<elem> = A.new(...)
.
Update: For an hash of array of A
, you need to do basically the same thing, you just need to be explicit about the types at every step:
sub test_hash() returns Hash[Array[A]] {
my Array[A] %ret;
%ret<elem> = Array[A].new(A.new(member => 'aaa'));
return %ret;
}
But don't exaggerate it; Perl 6 isn't as strongly typed as Haskell, and trying to act as if it were won't make for a good coding experience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With