12. The rules

In this chapter, you write the rules of the game, and compute the next generation.

The rules as clauses

Here are the rules from chapter 11 again.

  • A living cell with two or three living neighbors stays alive.
  • A dead cell with exactly three living neighbors comes to life.

alive_next(Live, Cell) is true when Cell is alive in the next generation. Each rule becomes one clause.

% A living cell with two or three living neighbors stays alive.
alive_next(Live, Cell) :-
    memberchk(Cell, Live),
    live_neighbors(Cell, Live, N),
    ( N =:= 2 ; N =:= 3 ).

% A dead cell with exactly three living neighbors comes to life.
alive_next(Live, Cell) :-
    \+ memberchk(Cell, Live),
    live_neighbors(Cell, Live, 3).

Compare the comments with the code. The code says the same thing as the English, in the same order. There is no if statement that checks the state of the cell and then updates a variable. You wrote when a cell is alive, and that is all.

The third rule, "every other cell is dead", needs no code. A cell is dead in the next generation when alive_next/2 can't prove that it is alive. This is negation as failure from chapter 9.

Which cells to check

The board has no edges, so we can't check every cell. But a cell can be alive in the next generation only if it is alive now, or if it is next to a living cell. So those are the only candidates.

candidate(Live, C) :- member(L, Live), ( C = L ; neighbor(L, C) ).

The next generation

Now step/2 finds all candidates, removes duplicates, and keeps the ones that are alive next.

step(Live, Next) :-
    findall(C, candidate(Live, C), Candidates0),
    sort(Candidates0, Candidates),
    findall(C, (member(C, Candidates), alive_next(Live, C)), Next).

Here is the whole program so far. The blinker is a row of three cells that turns into a column, and back into a row.

The first query turns the row [0-1, 1-1, 2-1] into the column [1-0, 1-1, 1-2]. The second query takes two steps, and the blinker is back as a row.

Asking about one cell

Because alive_next/2 is a relation, you can also ask questions that a loop over an array can't answer so easily. For example, which cells come to life in the next step?

Try it

  1. A 2 by 2 square [0-0, 0-1, 1-0, 1-1] is called a "block". Check that one step doesn't change it.
  2. Write dies(Live, Cell), which finds the living cells that die in the next step. Find the cells that die in the blinker.
An unhandled error has occurred. Reload 🗙