in reply to Prolegemona To A Future Scripting Language: Game Of Life In Perl 6
That's a great effort, especially without a compiler.
Here are a few corrections and some more "idiomatic" solutions.
# CREATE is something else entirely (see Apocalypse 12 ;-)
# Have to declare it when dimension known (i.e. in
# constructor) and then bind it to attribute
Comments in bold italics explain corrections on the previous line.
Comments in normal italics explain stylistic choices on the previous line.
# Indirect object syntax requires colon after invocantmy $life = new life: 20;
# Argumentless &loop is cleaner that &while for infinite loopsloop { $life.display() }
# Bit is potentially much smaller than Int for 1/0 valuesclass life { has Int $.count; has Int $.max; has Array of Bit @.grid;
# BUILD is the object initializer.method BUILD(Int $dim)
# CREATE is something else entirely (see Apocalypse 12 ;-)
# Setting default value to 0 reduces initialization costs{ $.count = 0; $.max = $dimension-1; my Array of Bit @grid is dim($dim,$dim) is default(0);
# Can't declare variably dimensioned array as attribute.@grid[$dim / 2 - 1][$dim / 2 ] = 1; @grid[$dim / 2 - 1][$dim / 2 + 1] = 1; @grid[$dim / 2 ][$dim / 2 ] = 1; @grid[$dim / 2 ][$dim / 2 - 1] = 1; @grid[$dim / 2 + 1][$dim / 2 ] = 1; @.grid := @grid;
# Have to declare it when dimension known (i.e. in
# constructor) and then bind it to attribute
# Utility sub to factor out repetitive 2D iterations} sub iterate (&block)
# Prefer &for over &loop when possible (e.g. here){ for 0..$.max -> $x
# Pass &iterate a block with placeholders for $x and $y{ for 0..$.max -> $y { block($x,$y); } } } method calculate() is private { my @newgrid; iterate { my $live = sum(@.grid[$^x-1..$^x+1][$^y-1..$^y+1]); @newgrid[$^x][$^y] = $live==2 && @.grid[$^x][$^y] || $live==3; }
# STDIN is now $*IN@.grid = @newgrid; } method display { iterate { print $.grid[$^x][$^y] ?? '+' :: '.'; print "\n" if $^x == $.max; } print "\n"; print "Turn $(++$.count), press enter to continue or ctl-c to quit +; <$*IN>;
Update: Fixed display method (thanks jkahn).calculate(); } }
In Section
Cool Uses for Perl