Conway’s Game of Life in Elm

Robert J Woodhead
2 min readFeb 14, 2017

--

So as not to bury the lede, you can play with the app here…

I’m always on the lookout for new and interesting programming environments, and for the last few months I’ve been noodling around with Elm.

Elm is a really interesting functional programming language for writing web applications. What makes it particularly attractive is The Elm Architecture, which embeds your purely functional Elm code into a simple and clever loop:

  • The user does something on the webpage, which…
  • Causes messages to be sent to an update function you write, which…
  • Updates a model that describes the complete state of your application, which…
  • Is passed to a view function you write that computes what the page should now look like, which…
  • Causes the page to be efficiently updated, ready for the user to do something else. Lather, rinse, and repeat!

The Elm language has a simplicity and elegance that appeals to me on an aesthetic level. It’s strongly typed and the compiler bends over backwards to be helpful in pointing out your mistakes. In fact, if your code compiles, it will run — no exceptions! And by that I mean: your code will not generate any exceptions at runtime.

Needless to say, even though you can rely on your code to do what you tell it to do, it may not do what you want it to do. However, since the complete state of your application is in the model, Elm can implement a time-traveling debugger — you can literally rewind the app state at will!

Recently, I decided I wanted to dig a little deeper and “grok” Elm better, so I decided to implement Conway’s Game of Life in Elm. Implementing Life has for many years been one of my go-to test exercises when getting used to a new programming language, so it was nice to return to familiar territory.

I ended up with an app that can:

  • Single-step or free-run life generations at various speeds. The board can be set to automatically expand or have edges that wrap.
  • Edit, shift, rotate, minimize, zoom, clear and “soup” the board.
  • Import boards in .cell and .rle formats, export in .cell.
  • Load prestored patterns.
  • Detects if running on a touch device and respond accordingly.
  • Autoresize.

Along the way, I learned a lot of intermediate techniques in Elm, including using application flags, javascript ports, subscriptions, currying, pipelines, pattern matching, mapping, filtering and folding, and using the Random library. I also got a lot more familiar with the Bootstrap.css framework.

The source code is available on GitHub — profusely commented both for the benefit of fellow newbies and the amusement of more experienced Elm programmers. I’m also hosting the built application here.

Enjoy! And suggestions, bug-reports, etc., are always appreciated.

PS: I found the KnowThen.com online courses very helpful in learning the basics of Elm. Check them out, the first one is free.

--

--