Skip to content

Numbers in Perl 6

James E Keenan edited this page Feb 7, 2016 · 15 revisions

Study questions pertaining to numbers.

  1. How are numbers stored in P6?
my $integer = 6;
my $rational = 6/5;
my $next = 9/3;
my $pi = 3.1415926;

say $integer;
say $rational;
say $next;
say $pi;
say '';
say $integer.WHAT;
say $rational.WHAT;
say $next.WHAT;
say $pi.WHAT;
say '';
say $integer.perl;
say $rational.perl;
say $next.perl;
say $pi.perl;

Output:

$ p6 numbers.pl6 
6
1.2
3
3.1415926

(Int)
(Rat)
(Rat)
(Rat)

6
1.2
3.0
3.1415926
# http://perl6intro.com/#_scalars
say "numerator: ", $rational.numerator;
say "denominator: ", $rational.denominator;
say "nude: ", $rational.nude

"nude" = nu + de (list of numerator and denominator)

Output:

numerator: 6
denominator: 5
nude: (6 5)

"base-repeating" functionality:

my ($fraction, $non-rep, $repeating);
$fraction = 19/3;
($non-rep, $repeating) = ($fraction).base-repeating(10);
say "non-rep:   <", $non-rep, '>';
say "repeating: <", $repeating, '>';
say "";
$fraction = 17/5;
($non-rep, $repeating) = ($fraction).base-repeating(10);
say "non-rep:   <", $non-rep, '>';
say "repeating: <", $repeating, '>';

Output:

non-rep:   <6.>
repeating: <3>

non-rep:   <3.4>
repeating: <>
```__
Use of '_' for readability:
```perl6
my $x = 5_00000;
say q|Type an integer 5_00000; it comes back as: |, $x;

Output:

Type an integer 5_00000; it comes back as: 500000

Radix notation: for expressing integers in bases other than base 10:

my $ox = :8<63>;
my $hx = :16<a1>;

say $ox;
say $hx;

Output:

51
161
my $p = 17;
my $q = 18;
say $p.is-prime;
say $q.is-prime;

Output:

True
False

Octals are handled differently from in Perl 5:

$ perl -E 'say 073'
59
$ perl6 -e 'say 073'
Potential difficulties:
    Leading 0 does not indicate octal in Perl 6.
    Please use 0o73 if you mean that.
    at -e:1
    ------> say 073⏏<EOL>
73
$ perl6 -e 'say 0o73'
59

But hexadecimals appear to be similar to Perl 6.

$ perl -E 'say 0xa1'
161
$ perl6 -e 'say 0xa1'
161

Transform an integer into the corresponding character:

say "chr  86: ", chr  86;
say "chr 186: ", chr 186;
say "chr 286: ", chr 286;
say "chr 386: ", chr 386;
say "";
say " 86.chr: ",  86.chr;
say "186.chr: ", 186.chr;
say "286.chr: ", 286.chr;
say "386.chr: ", 386.chr;

Output:

chr  86: V
chr 186: º
chr 286: Ğ
chr 386: Ƃ

 86.chr: V
186.chr: º
286.chr: Ğ
386.chr: Ƃ

The ```expmod`` method takes an integer, raises it to a power, divides it by the modulus, then returns the remainder.

my ($power, $modulus);
$integer = 3;
$power = 4;
$modulus = 7;
say "expmod($integer, $power, $modulus): ", expmod($integer, $power, $modulus);
say $integer ~ '.expmod(' ~ $power ~ ', ' ~ $modulus ~ '): ', $integer.expmod($power, $modulus);

Output:

expmod(3, 4, 7): 4
3.expmod(4, 7): 4
Clone this wiki locally