From a0cb250f24d5cf59cb26fff42ba6100f355fdf19 Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Mon, 3 Aug 2015 17:52:00 -0500 Subject: [PATCH] Fix multi-statement 'for' with 'else' and add test cases for 'else' --- hy/core/macros.hy | 11 ++++++++--- tests/native_tests/language.hy | 6 ++++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/hy/core/macros.hy b/hy/core/macros.hy index 517b7cb..6a8709f 100644 --- a/hy/core/macros.hy +++ b/hy/core/macros.hy @@ -97,16 +97,21 @@ (for* [x foo] (for* [y bar] baz))" + (setv body (list body)) + (setv lst (get body -1)) + (setv belse (if (and (isinstance lst HyExpression) (= (get lst 0) "else")) + [(body.pop)] + [])) (cond [(odd? (len args)) (macro-error args "`for' requires an even number of args.")] [(empty? body) (macro-error None "`for' requires a body to evaluate")] - [(empty? args) `(do ~@body)] - [(= (len args) 2) `(for* [~@args] (do ~@body))] + [(empty? args) `(do ~@body ~@belse)] + [(= (len args) 2) `(for* [~@args] (do ~@body) ~@belse)] [true (let [[alist (cut args 0 nil 2)]] - `(for* [(, ~@alist) (genexpr (, ~@alist) [~@args])] ~@body))])) + `(for* [(, ~@alist) (genexpr (, ~@alist) [~@args])] (do ~@body) ~@belse))])) (defmacro -> [head &rest rest] diff --git a/tests/native_tests/language.hy b/tests/native_tests/language.hy index 085e503..d468533 100644 --- a/tests/native_tests/language.hy +++ b/tests/native_tests/language.hy @@ -95,8 +95,10 @@ (setv count 0) (for [x [1 2 3 4 5] y [1 2 3 4 5]] - (setv count (+ count x y))) - (assert (= count 150)) + (setv count (+ count x y)) + (else + (+= count 1))) + (assert (= count 151)) (assert (= (list ((fn [] (for [x [[1] [2 3]] y x] (yield y))))) (list-comp y [x [[1] [2 3]] y x]))) (assert (= (list ((fn [] (for [x [[1] [2 3]] y x z (range 5)] (yield z)))))