perl6/rakudo:如何更改变量的数据类型?

发布于 2024-10-17 22:33:05 字数 422 浏览 7 评论 0原文

#!perl6
use v6;

my $m = 70;
my $n = 30;

( $m div $n ).say;

第一个示例有效,但第二个示例无效。我想这是因为在第二个示例中变量值是字符串。如果我的猜测是正确的,我如何将字符串变量更改为整数变量?

#!perl6
use v6;

my $m = '70';
my $n = '30';

( $m div $n ).say;


# No applicable candidates found to dispatch to for 'infix:<div>'. 
# Available candidates are:
# :(Int $a, Int $b)

#   in main program body at line 7:./perl5.pl
#!perl6
use v6;

my $m = 70;
my $n = 30;

( $m div $n ).say;

The first examples works, but the second doesn't. I suppose it's because in the second example the variable-values are strings. If my guess is right, how could I change the string-variables to integer-variables?

#!perl6
use v6;

my $m = '70';
my $n = '30';

( $m div $n ).say;


# No applicable candidates found to dispatch to for 'infix:<div>'. 
# Available candidates are:
# :(Int $a, Int $b)

#   in main program body at line 7:./perl5.pl

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

节枝 2024-10-24 22:33:05

你总是可以手动转换为 Int

( $m.Int div $n.Int ).say;

实际上我希望前缀:<+>会像中那样工作,

( +$m div +$n ).say;

但它只是“Num”,并且 sig 需要“Int”,我不确定是否应该这样。

更新:+$m 现在可以工作了。

You can always manually cast to Int

( $m.Int div $n.Int ).say;

Actually I would have hoped that prefix:<+> would work as in

( +$m div +$n ).say;

But it just "Num"ifies and the sig requires "Int", I am not sure if it should be this way or not.

UPDATE: +$m now works.

笑饮青盏花 2024-10-24 22:33:05

我有点认为第二种形式也应该有效(首先强制转换为 Int,然后进行整数除法)。我将从其他 Perl 6 开发人员那里得到一些反馈,如果他们同意,我会修复它。 (更新:事实证明 infix: 显然不是强制的,而是指定返回与参数相同类型的值。这通常不适用于 Str)。

正如 Pat 指出的那样,+$m 也应该有效,这是 Rakudo 中长期存在的限制。

一般来说,类型的强制转换是通过 $variable.Typename 完成的,我相信这适用于当今 Rakudo 中的所有数字类型。

I kinda think that the second form should work too (coerce to Int first, and then do integer division). I'll get some feedback from the other Perl 6 developers, and fix it if they agree. (Update: turns out that infix: is explicitly not coercive, but rather is specced to return a value of the same type as the arguments. Which won't work for generally for Str).

As Pat pointed out, +$m should also work, that's a long standing limitation in Rakudo.

In general, coercion to a type is done with $variable.Typename, and I believe this works for all numeric types in Rakudo today.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文