Learning Perl 6 by playing silly games
Posted on 07 September 2010
So I decided to take the plunge and see what Rakudo* has to offer and what Perl 6 is like as a language. I’ve always found the best way to learn programming is through examples and by doing tasks, so when I found the perl6-examples collection, I started to go through the 99-problems one by one.
Although I started out writing “baby” perl 6, I quickly found that other people’s solutions to the problems were shorter – and clearer – than my own. It’s quickly become clear that the menagerie of perl 6 operators is more expressive than I ever imagined possible. I’ve never complained that a language lacked a particular operator, or that a language should be extended by adding more operators. Perl 6 may be changing my mind.
Today all this was made clear by a silly example in #perl6: noughts and crosses! (or tic-tac-toe, if you prefer.) The problem: given a noughts-and-crosses grid, where the players are 1,-1 and the empty squares 0, determine who, if anyone, has won. Here’s the first example that masak made:
He uses a slicel
function to create cross-cutting slices of
multidimensional arrays, and uses his list of lines to go through all
possibilities, finding a winner. He also takes advantage of the [==]
reduction metaoperator: [==]
results in a == b && b == c
. The
reduction metaoperator can also create such useful functions as [+]
sum and [*]
product, which in other languages would require a
separate function call. In Perl 5, for example, product is reduce {
$a * $b }
using reduce
from List::Util
.
Here’s my improvement:
By flattening the board array, I avoided the need for a slicel
function; I also used the X+
cross metaoperator to shorten creating
the lines. Xop <1 2 3>
gives a op 1, a op 2, a op 3, b op 1, b op
2, b op 3, c op 1, c op 2, c op 3
. Then
moritz_ pointed out that 0,1,2
can be
written using the upto operator: ^3
:
Further refinements are possible: 0,3,6
is ^3 »*» 3
, using the
hyper operator to multiply each of 0,1,2
by 3. But by this point,
we’re just using different Perl 6 operators for the sake of it, not
because it makes the code clearer. Like code golf, this is hackers at
play; and while the product is not something necessarily useful, the
learning I’ve gained from it is invaluable.