removed guard as it matches cond almost exactly, added case

This commit is contained in:
Matthias Pall Gissurarson 2015-01-18 12:34:07 +00:00
parent a3670a8d57
commit 7be22e361b
2 changed files with 24 additions and 23 deletions

View File

@ -2,7 +2,7 @@
Flow Flow
========== ==========
.. versionadded:: 0.10.2 .. versionadded:: 0.10.1
The ``flow`` macros allow a programmer to direct the flow of his program with The ``flow`` macros allow a programmer to direct the flow of his program with
greater ease. greater ease.
@ -11,16 +11,16 @@ greater ease.
Macros Macros
====== ======
.. _guard: .. _case:
.. _switch: .. _switch:
guard case
----- -----
``guard`` allows you to guard against a condition. ``case`` allows you to decide based on the value of a variable.
Usage: `(guard (cond1) (body1) (cond2) (body2) ...)` Usage: `(case variable val1 (body1) val2 (body2) ...)`
Example: Example:
@ -28,11 +28,12 @@ Example:
(require hy.contrib.flow) (require hy.contrib.flow)
(defn army-greeter [age height] (defn bmi-commenter [bmi]
(guard (case bmi
(< age 18) (print "You are too young!") 10 (print "The bmi was 10, wow.")
(< height 170) (print "You are too small!") 20 (print "20? Really?")
True (print "Welcome aboard!"))) 30 (print "Was it 30? Ok...")
(print "I don't even know.")))
switch switch
@ -54,6 +55,6 @@ Example:
(switch bmi (switch bmi
(<= 18.5) (print "you are underweight!") (<= 18.5) (print "you are underweight!")
(<= 25.0) (print "apparently normal") (<= 25.0) (print "apparently normal")
(<= 30) (print "a little too heavy, but ok") (<= 30.0) (print "a little too heavy, but ok")
(print "You are a whale!"))) (print "You are a whale!")))

View File

@ -1,15 +1,5 @@
;; Additional flow macros ;; Additional flow macros
(defmacro/g! guard [&rest args]
(setv g!cond (car args))
(setv g!body (car (cdr args)))
(setv g!rest (cdr (cdr args)))
(if g!rest
`(if ~g!cond
~g!body
(guard ~@g!rest))
`(if ~g!cond
~g!body)))
(defmacro/g! switch [variable &rest args] (defmacro/g! switch [variable &rest args]
(setv g!comp (car args)) (setv g!comp (car args))
@ -22,3 +12,13 @@
`(if ~g!cond ~g!body ~@g!rest)) `(if ~g!cond ~g!body ~@g!rest))
`(if ~g!cond ~g!body))) `(if ~g!cond ~g!body)))
(defmacro/g! case [variable &rest args]
(setv g!value (car args))
(setv g!body (car (cdr args)))
(setv g!rest (cdr (cdr args)))
(setv g!cond `(= ~variable ~g!value))
(if g!rest
(if (cdr g!rest)
`(if ~g!cond ~g!body (case ~variable ~@g!rest))
`(if ~g!cond ~g!body ~@g!rest))
`(if ~g!cond ~g!body)))