Skip to content

Instantly share code, notes, and snippets.

@lomin
Created January 6, 2012 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lomin/1572062 to your computer and use it in GitHub Desktop.
Save lomin/1572062 to your computer and use it in GitHub Desktop.
Game of Life in Clojure (modified from http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/)
(ns gol)
(defn grid-with-center [[x y]]
(let [deltas [-1 0 1]]
(for [delta-x deltas delta-y deltas]
[(+ x delta-x) (+ y delta-y)])))
(defn center? [center]
(partial = center))
(defn neighbours [cell]
(remove (center? cell) (grid-with-center cell)))
(defn all-neighbours-of [cells]
(mapcat neighbours cells))
(defn will-live? [cell quantity lives?]
(or
(= quantity 3)
(and (= quantity 2)
(lives? cell))))
(defn step [living-cells]
(set
(for [[cell quantity] (frequencies (all-neighbours-of living-cells))
:when (will-live? cell quantity living-cells)]
cell)))
(def living-cells #{[1 0] [1 1] [1 2]})
(take 5 (iterate step living-cells))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment