PERL6 / RAKUDO: كيف يمكنني تغيير نوع البيانات من متغير؟

StackOverflow https://stackoverflow.com/questions/5050210

سؤال

giveacodicetagpre.

الأمثلة الأولى تعمل، ولكن الثانية لا.أفترض أنه لأنه في المثال الثاني القيم المتغيرة هي سلاسل.إذا كان تخميني على حق، فكيف يمكنني تغيير متغيرات السلسلة إلى المتغيرات العددية؟ giveacodicetagpre.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top