[Purdue-pm] a Perl 6 quick example
Mark Senn
mark at purdue.edu
Tue Dec 13 21:59:40 PST 2016
# The "is-prime" sub is defined in Perl 6.
is-prime(5)
True
# The parentheses are not needed.
is-prime 5
True
# The "is-prime" method is defined in Perl 6.
5.is-prime
True
# Get all primes from 2 to 10.
grep {$_.is-prime}, (2..10)
(2 3 5 7)
# If an object is not specified, "$_" is assumed.
grep {.is-prime}, (2..10)
(2 3 5 7)
# Get first three primes---I know the third prime comes before 10.
(grep {.is-prime}, (2..10))[0..2]
(2 3 5)
# Using "^3" will give first three also---I think of "^3"
# as from 0 up to but not including 3.
(grep {.is-prime), (2..10))[^3]
(2 3 5)
# Let Perl 6 generate as many candidate integers
# as we need (from 2 to infinity) to test for
# primality but stop after we get 3 primes.
(grep {.is-prime}, (2..Inf))[^3]
(2 3 5)
# Use "*" ("whatever") instead of "Inf".
# Instead of 2 to infinity think of it
# as 2 to whatever.
(grep {.is-prime}, (2..*))[^3]
(2 3 5)
# Exercise for the reader, do the previous
# computation in Perl 5 but make the code
# at least as clear as the Perl 6 solution.
# Perl 6 uses really big integers in software
# if an integer is too big for machine computation.
10**1000 - 3
99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999!
99999999997
-mark
More information about the Purdue-pm
mailing list