arrays - 如何将结点中的值作为数组返回?

标签 arrays raku junction

定义一个结点 my $j = 1 | 2 | 3 | 4 | 5 ,现在我想获取其值的数组 [1 2 3 4 5] ,我应该如何实现这个?

我试过 $j.values但是 Perl6 给了我整个结点作为一个元素:[any((1), (2), (3), (4), (5))] .

最佳答案

正如 Håkon Hægland 已经指出的,这不是你应该做的事情:

Junctions are meant to be used as matchers in boolean context; introspection of junctions is not supported. If you feel the urge to introspect a junction, use a Set or a related type instead.

 -- docs.perl6.org/type/Junction



然而,这是可能的。

首先,您可以使用自动线程(即,当传递给需要类型为 Any 的参数的函数时,对连接的每个分支的自动评估):
sub unjunc(Junction $j) {
    gather -> Any $_ { .take }.($j);
}

其次,您可以深入了解并手动提取值:
sub unjunc(Junction $j) {
    multi extract(Any $_) { .take }
    multi extract(Junction $_) {
        use nqp;
        my $list := nqp::getattr($_, Junction, '$!storage');
        my int $elems = nqp::elems($list);
        loop (my int $i = 0; $i < $elems; $i = $i + 1) {
            extract nqp::atpos($list, $i);
        }
    }
    gather extract $j;
}

如果您的结点是非递归的(即不包含要展平的其他结点),则可以简化后一种方法:
my $j := 1|2|3;
say nqp::p6bindattrinvres(nqp::create(List), List, '$!reified',
    nqp::getattr($j, Junction, '$!storage'));

关于arrays - 如何将结点中的值作为数组返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43568394/

相关文章:

c - 扫描二维字符数组

r - 如何在 raku-lang 中连接两个矩阵?

io - Perl6 : run command as a different user

winapi - NTFS Junctions,难以理解 API

Java - CSVReader 在值中用逗号正确分割

ios - 从NSMutableArray提取特定数据的更快方法?

windows - 如何使用 WinApi 创建连接点?

php - Yii 多对多,联结表对象图

python - 扁平化numpy数组,还能保留值位置的索引?

python - 我知道 Perl 5。学习 Perl 6 而不是转向 Python 有什么好处?