From d3df17d9d8d5a154f50dcc754b6b9cc760e337b6 Mon Sep 17 00:00:00 2001 From: neil-lindquist Date: Fri, 9 Jun 2017 20:22:23 -0500 Subject: [PATCH] Modify cond to support single argument branches --- NEWS | 1 + docs/language/api.rst | 12 ++++++++++++ hy/core/macros.hy | 8 ++++---- tests/native_tests/language.hy | 12 +++++++++++- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/NEWS b/NEWS index e5b6a63..763d680 100644 --- a/NEWS +++ b/NEWS @@ -32,6 +32,7 @@ Changes from 0.12.1 `(try 1 (except [ValueError] 2) (else 3))` returns `3`. * xor: If exactly one argument is true, return it * hy.core.reserved is now hy.extra.reserved + * cond now supports single argument branches [ Bug Fixes ] * All shadowed operators have the same arities as real operators diff --git a/docs/language/api.rst b/docs/language/api.rst index a3d81e1..a31b6c8 100644 --- a/docs/language/api.rst +++ b/docs/language/api.rst @@ -374,6 +374,18 @@ shows the relationship between the macro and its expansion: (if condition-1 result-1 (if condition-2 result-2)) +If only the condition is given in a branch, then the condition is also used as +the result. The expansion of this single argument version is demonstrated +below: + +.. code-block:: clj + + (cond [condition-1] + [condition-2]) + + (if condition-1 condition-1 + (if condition-2 condition-2)) + As shown below, only the first matching result block is executed. .. code-block:: clj diff --git a/hy/core/macros.hy b/hy/core/macros.hy index c96feb1..e1ca49a 100644 --- a/hy/core/macros.hy +++ b/hy/core/macros.hy @@ -56,10 +56,10 @@ (if (not (= (type branch) HyList)) (macro-error branch "cond branches need to be a list")) (if (< (len branch) 2) - (macro-error branch "cond branches need at least two items: a test and one or more code branches")) - (setv test (first branch)) - (setv thebranch (cut branch 1)) - `(if ~test (do ~@thebranch))) + (do + (setv g (gensym)) + `(if (do (setv ~g ~(first branch)) ~g) ~g)) + `(if ~(first branch) (do ~@(cut branch 1))))) (setv root (check-branch branch)) (setv latest-branch root) diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 1baaedd..49b5305 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -291,7 +291,17 @@ (cond [(= 1 2) (assert (is True False))] [(is None None) (setv x True) (assert x)]) - (assert (= (cond) None))) + (assert (= (cond) None)) + + (assert (= (cond + [False] + [[]] + [8])) 8) + + ;make sure test is only evaluated once + (setv x 0) + (cond [(do (+= x 1) True)]) + (assert (= x 1))) (defn test-if []