Conway’s Game of Life
APL is famous for having a 1-liner for Conway’s game of life.
Being very efficient at implementing a matrix-based solution of Conway’s game of life should come to no suprise from an array-oriented language.
The way you model data determines your code. Clojure encourages what I call relational-oriented programming. That is modeling with sets, natural identifiers (thanks to composite values) and maps-as-indexes.
If you pick the right representation for the state of the board, you end up with a succinct implementation:
(defn neighbours [[x y]] (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])] [(+ dx x) (+ dy y)])) (defn step [cells] (set (for [[loc n] (frequencies (mapcat neighbours cells)) :when (or (= n 3) (and (= n 2) (cells loc)))] loc)))
Let’s see how it behaves with the “blinker” configuration:
(def board #{[1 0] [1 1] [1 2]}) ; #'user/board (take 5 (iterate step board)) ; (#{[1 0] [1 1] [1 2]} #{[2 1] [1 1] [0 1]} #{[1 0] [1 1] [1 2]} #{[2 1] [1 1] [0 1]} #{[1 0] [1 1] [1 2]})
Great, it oscillates as expected!
From this step
can be distilled a generic topology-agnostic life-like automatons stepper factory (phew!) but this is a subject for another post or — shameless plug — a book.
I couldn’t believe that such a short solution could possibly work, so I copied it into my IDE to play around with it. I verified that a glider worked and that a 3 cell diagonal died off as expected.
Very cool!
Can’t wait for your book to come out.
You make your point with elegance. impressive!
[...] Otherwise here is a beautiful implementation of Conway’s Game of Life by Christophe Grand: [...]
[...] and Rupert decided to look at someone else’s solution in Clojure, to understand how a functional approach using list comprehensions can lead to a very concise [...]
[...] 另外,下面是一个由Christophe Grand实现的生命游戏的Clojure版本: [...]
[...] session se termine par une session de coding pré-enregistrée, montrant l’implémentation du jeu de la vie de Conway. Les résultats intermédiaires sont affichés après chaque fonction développée, ce qui [...]
I put together a screencast of building this solution interactively in Clojure for a presentation: check it out here if you’re interested… http://www.youtube.com/watch?v=lgsAztXDuH0
[...] Christophe’s Game of Life [...]
[...] 另外,下面是一个由Christophe Grand实现的生命游戏的Clojure版本: (defn neighbours [[x y]] (for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])] [(+ dx x) (+ dy y)])) [...]
I wrote an in-depth explanation of your solution. It should be understandable to non-Clojure programmers and newcomers.
http://programmablelife.blogspot.com/2012/08/conways-game-of-life-in-clojure.html
[…] implémentation java de la solution ultra bref en […]
Hi, Christophe. This beautiful solution results from the insight that everything you need is in the neighbors collection. It is not simply the result of using Clojure, although Clojure certainly makes the solution succinct. Do you agree?
Arthur
[…] of the more remarkable implementations of Life that I’ve uncovered is written in Clojure, and may be found here. There is also a one line implementation written in APL, but I find it entirely […]
It’s a pity you don’t have a donate button! I’d definitely donate to this excellent blog!
I guess for now i’ll settle for book-marking and adding
your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group.
Talk soon!
Numerous gamers possess a personalized principle that they instantly stop when they attain the point whereby they.
[…] My favorite implementation is from Christophe Grand. It’s just so small. It shows that you can turn the problem inside out from how it is normally solved. All you have to do it peer hard into the heart of the problem. […]
[…] got shocked when I see this 7 line solution in Clojure. I had to write nearly a 100 line of code in Java to do the […]
[…] Conway’s Game of Life in Clojure (2011) 2 by simonpure | 0 comments on Hacker News. […]
[…] Conway’s Game of Life in Clojure (2011) 3 by simonpure | 0 comments on Hacker News. […]
Of course, what a great blog and revealing posts, I surely will bookmark your website.Best Regards!
Perch, my favourite species Hook Line Bid Blog
purses too. I personally believe that any one of those totes
Utterly written subject matter, appreciate it for selective information.
I really liked your blog article.Thanks Again. Awesome.
This is a very good tip particularly to those new to the blogosphere. Short but very accurate information Many thanks for sharing this one. A must read article!
This is the very first time I frequented your website page and thus far? I surprised with the research you made to create this particular publish incredible.
крышка airbag руля
Нож как режущий инструмент – это один из самых известных инструментов. Обработка продуктов и материалов, строительные, садоводческие работы – для всего этого режущий инструмент просто необходим.
Хотите более подробно ознакомиться с полезной информацией о ножах? В интернете существует такой проект – интернет-сайт: vashnozh.ru
Рассматриваются такие материалы как:
– Авторские материалы о ножах;
– Модели, история создания и заточки ножей;
– Горячие подборки новостей из мира ножей и режущих инструментов
– FAQ по ножам: ножи для специфических кулинарных действий, чем отличается нож для сыра от ножа для мяса или рыбы?
– Инструкции по использованию ножей в разделке мяса, рыбы и других продуктов. Интернет-сайт целиком и полностью посвящен ножам и их функциональности.
Наша команда создает и распространяет информацию о ножах в мирных целях. Переходите на интернет-сайт и подписывайтесь на новые статьи.
Если это сообщение попало не туда, просим перенести туда, куда следует размещать такие топики.