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]
This commit is contained in:
agentultra 2013-11-28 16:15:23 -05:00
parent 2106a0e5d4
commit 8e44cc3d9a
2 changed files with 30 additions and 0 deletions

View File

@ -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]

View File

@ -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]))