Clojure — Conway’s Game of Life

Dan Pelensky
3 min readAug 1, 2017

I’ve recently been working on Conway’s Game of Life in Clojure.

[Conway’s Game of Life] is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves, or, for advanced “players”, by creating patterns with particular properties.

This may sound familiar, as I did a series on the Game of Life in Java. Links here:

  1. Setup
  2. Generations
  3. Command Line Interface

When I was challenged to do it again in Clojure, I thought it would be easy as I didn’t find it too difficult in Java and I’ve had two months more experience writing code since then. I thought I was going to get through it in a half day but when I went to write the first test I could not think of where to start. Here’s where I got:

In my Java implementation I hadn’t created an infinite world; I created a finite grid where each cell in the grid was instantiated with either a living or non-living cell object. Each cell was given a trigger to evolve, and based on logic inside the cell it would return either a living or a not living cell.

That implementation worked great for a finite world in an object oriented language but in a functional language with an infinite world I needed to go back to the drawing board.

When I went to start this again, I tried Katerina’s strategy of beginning with the display. This was something that I could tangibly see and I was delighted that I had a starting place:

(describe "Display grid"
(it "prints an empty grid as an empty string"
(should-contain ""
(with-out-str (display #{}))))

With TDD, I was able to flesh out my display and decided to use a set of coordinates for living cells as the data that I would pass in to my functions. I continued writing tests and code until I came up with a recursive function that would display an infinite world based on the coordinates of the living cells.

Once I had my display working I started the logic to evolve cells to the next generation. Again, I started with the easiest test I could think of:

(describe "Life"
(it "An empty grid stays empty"
(should= #{}
(evolve #{})))

I subsequently fleshed this out into code that finds all the living cells and their neighbours, and based on whether they are alive in the current generation or not and the number of neighbours they have, they they will be alive in the next generation or not.

I really enjoyed writing the Game of Life in Clojure, and I think the code is much simpler than it was in Java. I find it very fun to get the opportunity to solve a problem in a completely different way to what I’ve done before.

--

--