1
0
mirror of https://github.com/janet-lang/janet synced 2025-11-04 01:23:04 +00:00

Add generator expressions for easier iteration.

Similar to python generator, but with the same
syntax as the loop macro.
This commit is contained in:
Calvin Rose
2018-11-20 21:48:06 -05:00
parent 1e87b01e02
commit 184fe31e0c
4 changed files with 62 additions and 23 deletions

View File

@@ -1,6 +1,6 @@
# A game of life implementation
(def- windows
(def- window
(fora [x :range [-1 2]
y :range [-1 2]
:when (not (and (zero? x) (zero? y)))]
@@ -8,38 +8,37 @@
(defn- neighbors
[[x y]]
(mapa (fn [[x1 y1]] (tuple (+ x x1) (+ y y1))) windows))
(mapa (fn [[x1 y1]] (tuple (+ x x1) (+ y y1))) window))
(defn tick
"Get the next state in the Game Of Life."
[state]
(def neighbor-set (frequencies (mapcat neighbors (keys state))))
(def next-state @{})
(loop [coord :keys neighbor-set
:let [count (get neighbor-set coord)]]
(if (if (get state coord)
(or (= count 2) (= count 3))
(= count 3))
(put next-state coord true)))
next-state)
(def cell-set (frequencies state))
(def neighbor-set (frequencies (mapcat neighbors state)))
(fora [coord :keys neighbor-set
:let [count (get neighbor-set coord)]
:when (or (= count 3) (and (get cell-set coord) (= count 2)))]
coord))
(defn draw
"Draw cells in the game of life from (x1, y1) to (x2, y2)"
[state x1 y1 x2 y2]
(def cellset @{})
(loop [cell :in state] (put cellset cell true))
(loop [:before (print "+" (string.repeat "--" (inc (- y2 y1))) "+")
:after (print "+" (string.repeat "--" (inc (- y2 y1))) "+")
x :range [x1 (+ 1 x2)]
:before (file.write stdout "|")
:after (file.write stdout "|\n")
y :range [y1 (+ 1 y2)]]
(file.write stdout (if (get state (tuple x y)) "X " ". ")))
(file.write stdout (if (get cellset (tuple x y)) "X " ". ")))
(print))
#
# Run the example
#
(var *state* {'(0 0) true '(-1 0) true '(1 0) true '(1 1) true '(0 2) true})
(var *state* '[(0 0) (-1 0) (1 0) (1 1) (0 2)])
(loop [i :range [0 20]]
(print "generation " i)