An Example

One interesting pattern that occurs in Life is a Glider:

glider←3 3⍴1 1 1 1 0 0 0 1 0
glider
1 1 1
1 0 0
0 1 0

To see how the Glider evolves over the generations, we need to give it some space to move around. The Game of Life takes place on an infinite two-dimensional grid, but that might be a bit large for our computer! Let's start the Glider off in the bottom right-hand corner of a 10 x 10 grid:

For some more examples and a simple function to animate Life in APLX see here

How the APL code works

If you're completely new to APL, this explanation is probably not the place to start! However, you should be able to get some idea of what's happening even if the details are not yet clear. Just bear in mind that APL evaluates expressions from right to left unless you use parentheses.

To compute a new generation in the Game of Life we first need to find out how many neighbours each live cell has. To keep things simple let's consider the following 5x5 grid:

If we rotate each row of the grid one place left by using APL's Rotate function ⌽, each element is replaced by its right-hand neighbour. In other words, the new grid will have a 1 for all cells whose right-hand neighbour was 1:

1⌽currentGeneration
0 0 0 0 0
0 1 1 0 0
1 1 0 0 0
0 1 0 0 0
0 0 0 0 0

Similarly we can rotate right to find the left-hand neighbour by using ¯1⌽currentGeneration. By using APL's Outer Product operator ∘. together with the Rotate function we can get a set of three grids containing the left-hand neighbour, the original grid, and the right-hand neighbour:

The grid in the centre is our original grid, and the others give the neighbours above, below, left, right and diagonally.

Now we can find out how many neighbours each cell in the original grid has by summing the corresponding elements in each of the 9 grids. For a live cell this will give us 1 more than the number of neighbours - e.g. a '4' in the result means a cell has three neighbours. For a dead cell the result is just the number of neighbours:

The next step is best understood by first considering the two scores 4 and 3 separately

(a) A score of 4 corresponds either to a live cell with three neighbours or a dead cell with four neighbours. Only in the former case do we get a cell in the next generation - i.e. we get a cell if the score is 4 AND the cell is currently live. Here we're using APL's And function, ^