Perl6: Sub: restrict to static hash-return 类型
Perl6: Sub: restrict to static hash-return type
我想在 Perl6 中限制我的某些函数的 return 类型。
我知道,如何推导函数的正确 return 类型,returning Perl6 中的标量或数组,但我不知道,如果我使用散列,我该怎么做特定类型的 return 值?
示例:Array 方法可以在test_arr()
中看到,Hash 方法可以在test_hash()
中看到。所以我想指定 test_hash()
的 return 值为 return 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;
}
它真的和数组一样:
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;
}
注意你也可以写成%ret<elem> = A.new(...)
.
更新:对于A
数组的散列,你需要做基本相同的事情,你只需要在每一步明确类型:
sub test_hash() returns Hash[Array[A]] {
my Array[A] %ret;
%ret<elem> = Array[A].new(A.new(member => 'aaa'));
return %ret;
}
但不要夸大它; Perl 6 不像 Haskell 那样强类型化,并且试图表现得好像它是强类型的不会带来良好的编码体验。
我想在 Perl6 中限制我的某些函数的 return 类型。 我知道,如何推导函数的正确 return 类型,returning Perl6 中的标量或数组,但我不知道,如果我使用散列,我该怎么做特定类型的 return 值?
示例:Array 方法可以在test_arr()
中看到,Hash 方法可以在test_hash()
中看到。所以我想指定 test_hash()
的 return 值为 return 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;
}
它真的和数组一样:
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;
}
注意你也可以写成%ret<elem> = A.new(...)
.
更新:对于A
数组的散列,你需要做基本相同的事情,你只需要在每一步明确类型:
sub test_hash() returns Hash[Array[A]] {
my Array[A] %ret;
%ret<elem> = Array[A].new(A.new(member => 'aaa'));
return %ret;
}
但不要夸大它; Perl 6 不像 Haskell 那样强类型化,并且试图表现得好像它是强类型的不会带来良好的编码体验。