gpt4 book ai didi

raku - Perl 6 : writable multidimensional subscript access with AT-POS

转载 作者:行者123 更新时间:2023-12-04 23:12:27 25 4
gpt4 key购买 nike

您可以使用 AT-POS 轻松地允许下标访问您自己的类:

class Foo
{
has @.grid;

method AT-POS($x) is rw { return-rw @!grid[$x] }
method Str { '<' ~ @!grid.join(' ') ~ '>' }
method gist { self.Str }
}

my $foo = Foo.new(:grid(<a b c d e>));
say $foo;
say $foo[2];
$foo[3] = 'z';
say $foo;

输出:
<a b c d e>
c
<a b c z e>

但我需要二维下标访问。我已经想出了如何使这项工作适合阅读,但在写作时它就死了:

class Bar
{
has @.grid;

method AT-POS($y, $x) is rw { return-rw @!grid[$y;$x] }
method Str { '<' ~ @!grid».join(' ').join("\n ") ~ '>' }
method gist { self.Str }
}

my $bar = Bar.new(:grid(<a b c d e>, <f g h i j>, <k l m n o>));
say $bar;
say $bar[1;2];
$bar[2;3] = 'z';
say $bar;

输出:
<a b c d e
f g h i j
k l m n o>
h
Too few positionals passed; expected 3 arguments but got 2
in method AT-POS at ./p6subscript line 25
in block <unit> at ./p6subscript line 33

有什么办法可以使这项工作?

最佳答案

不知何故,AT-POS方法没有被调用。 documentation提到了 ASSIGN-POS 的使用相反,所以我们开始:

class Bar
{
has @.grid is rw;

method AT-POS($y, $x) is rw { say "AT-POS $y, $x"; return-rw @!grid[$y;$x] }
method ASSIGN-POS($y, $x, $new) { say "ASSIGN-POS $y, $x"; @!grid[$y;$x] = $new }
method Str { '<' ~ @!grid».join(' ').join("\n ") ~ '>' }
method gist { self.Str }
}

my $bar = Bar.new(:grid(<a b c d e>, <f g h i j>, <k l m n o>));
say $bar;
say $bar[1;2];
$bar[2;3] = 'z';
say $bar;

有趣的是,这会产生另一个错误:

Cannot modify an immutable List ((k l m n o))
in method ASSIGN-POS at semilist-so.p6 line 8
in block <unit> at semilist-so.p6 line 16

所以问题不是真正的语法,而是你正在使用不可变列表的事实。您应该使用 Array s,它们是可变的,你将能够做到这一点。

class Bar
{
has @.grid is rw;

method AT-POS($y, $x) is rw { return-rw @!grid[$y;$x] }
method ASSIGN-POS($y, $x, $new) { @!grid[$y;$x] = $new }
method Str { '<' ~ @!grid».join(' ').join("\n ") ~ '>' }
method gist { self.Str }
}

my $bar = Bar.new(:grid([<a b c d e>], [<f g h i j>], [<k l m n o>]));
say $bar;
say $bar[1;2];
$bar[2;3] = 'z';
say $bar;

关于raku - Perl 6 : writable multidimensional subscript access with AT-POS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com