flan/test/programs/match-enum.flan

45 lines
1014 B
Plaintext

;;;; match over an enum: the arms name members as keywords, a _ arm is the
;;;; rest, and a match that names neither every member nor _ is refused.
(defenum Dir [north east south west])
(defn turn [d Dir] Dir
(match d
:north :east
:east :south
:south :west
:west :north))
(defn name [d Dir] str
(match d
:north "north"
:south "south"
_ "sideways"))
(defn calls [] i32
(print "(called) ")
0)
;; The scrutinee is evaluated once, however many arms test it.
(defn once [] Dir
(calls)
:west)
;; recur from inside an arm: the arm is the loop's tail.
(defn steps-to-west [from Dir] i32
(loop [d from n 0]
(match d
:west n
_ (recur (turn d) (+ n 1)))))
(defn main [] i32
(print (steps-to-west :north)) (println "")
(println (name :north))
(println (name (turn :north)))
(println (name (turn (turn :north))))
(println (name (once)))
(match (turn :west)
:north (println "back to north")
_ (println "somewhere else"))
0)