Conway’s Game of Life in Clojure (2011)

栏目: IT技术 · 发布时间: 4年前

内容简介: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. Tha

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 .


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

CSS精粹

CSS精粹

Rachel Andrew / 曹明伦 / 人民邮电出版社 / 2007-10 / 39.00元

本书采用问答的形式,为CSS使用过程中一些有价值的经典问题提供了精彩的实践解决方案。本书内容包括文本样式、CSS图像、导航、表格数据、注册表和用户界面、浏览器和设置支持、CSS定位和布局以及未来相关技术。 本书的目标读者是每一个需要使作CSS的Web设计人员和开发人员。本书通过经典的问题和精彩的解答将理论融于实践,使每一个带着问题阅读本书的读者都能找到自己满意的答案。一起来看看 《CSS精粹》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具