-
Notifications
You must be signed in to change notification settings - Fork 32
Conway's game of life, transducers edition
Christophe Grand edited this page Sep 16, 2016
·
4 revisions
(require '[net.cgrand.xforms :as x])
(defn step [cells]
(into #{}
(comp
(x/for [[x y] % dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)])
(x/by-key identity x/count)
(x/for [[cell n] %
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell))
cells))
=> (def board #{[1 0] [1 1] [1 2]}) ; blinker
=> (take 5 (iterate step board))
(#{[1 0] [1 1] [1 2]} #{[1 1] [2 1] [0 1]} #{[1 0] [1 1] [1 2]} #{[1 1] [2 1] [0 1]} #{[1 0] [1 1] [1 2]})
Alternative impl:
(defn step [cells]
(x/into #{}
(comp
(x/for [[x y] % dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[[(+ dx x) (+ dy y)] 1])
(x/by-key (x/reduce +))
(x/for [[cell n] %
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell))
cells))