From 8e44cc3d9a4600eb6e256e14e4c50a22dd0b0d50 Mon Sep 17 00:00:00 2001 From: agentultra Date: Thu, 28 Nov 2013 16:15:23 -0500 Subject: [PATCH] Add --each-while and --map-when A couple of more macros: hy> (--each-while [1 2 3 4 5] (< it 3) (print it)) 1 2 3 hy> ```--each-while``` continues to evaluate the body form while the predicate form is true for each element in the list. ```--map-when``` uses a predicate form to determine when to apply the map form upon the element in the list: hy> (list (--map-when (even? it) (* it 3) [1 2 3 4])) [1, 6, 3, 12] --- hy/core/macros.hy | 17 +++++++++++++++++ tests/native_tests/core.hy | 13 +++++++++++++ 2 files changed, 30 insertions(+) diff --git a/hy/core/macros.hy b/hy/core/macros.hy index 91c477d..a3261ab 100644 --- a/hy/core/macros.hy +++ b/hy/core/macros.hy @@ -123,12 +123,29 @@ `(foreach [it ~list] ~@body)) +(defmacro --each-while [lst pred &rest body] + `(let [[p (lambda [it] ~pred)]] + (foreach [it ~lst] + (if (p it) + ~@body + (break))))) + + (defmacro --map [form lst] `(let [[f (lambda [it] ~form)]] (foreach [v ~lst] (yield (f v))))) +(defmacro --map-when [pred rep lst] + `(let [[p (lambda [it] ~pred)] + [f (lambda [it] ~rep)]] + (foreach [v ~lst] + (if (p v) + (yield (r v)) + (yield v))))) + + (defmacro --filter [form lst] `(let [[pred (lambda [it] ~form)]] (foreach [val ~lst] diff --git a/tests/native_tests/core.hy b/tests/native_tests/core.hy index cde0cb6..e14dc0f 100644 --- a/tests/native_tests/core.hy +++ b/tests/native_tests/core.hy @@ -399,6 +399,13 @@ (--each [1 2 3 4] (.append res it)) (assert-equal res [1 2 3 4])) + +(defn test-anaphoric-each-while [] + "NATIVE: testing anaphoric each-while" + (setv res []) + (--each-while [2 2 4 3 4 5 6] (even? it) (.append res it)) + (assert-equal res [2 2 4])) + (defn test-anaphoric-map [] "NATIVE: testing anaphoric map" (assert-equal (list (--map (* it 3) [1 2 3])) @@ -406,6 +413,12 @@ (assert-equal (list (--map (* it 3) [])) [])) + +(defn test-anaphoric-map-when [] + "NATIVE: testing anaphoric map-when" + (assert-equal (list (--map-when (even? it) (* it 2) [1 2 3 4])) + [1 4 3 8])) + (defn test-anaphoric-filter [] "NATIVE: testing anaphoric filter" (assert-equal (list (--filter (> it 2) [1 2 3 4]))