Merge pull request #788 from nicolas-p/ap-pipe-ap-compose

Added ap-pipe and ap-compose macros
This commit is contained in:
Gergely Nagy 2015-07-23 15:08:18 +02:00
commit 4642625378
4 changed files with 56 additions and 0 deletions

View File

@ -60,5 +60,6 @@
* Shrayas Rajagopal <shrayasr@gmail.com>
* Shenyang Zhao <dev@zsy.im>
* Zack M. Davis <code@zackmdavis.net>
* Nicolas Pénet <z.nicolas@gmail.com>
* Adrià Garriga Alonso <adria@monkingme.com>
* Antony Woods <antony@teamwoods.org>

View File

@ -195,3 +195,36 @@ first element instead. This exposes the element being iterated as
=>(ap-reduce (+ it acc) (range 10))
45
.. _ap-pipe:
ap-pipe
=========
Usage ``(ap-pipe value form1 form2 ...)``
Applies several forms in series to a value from left to right. The special variable ``ìt`` in each form is replaced by the result of the previous form.
.. code-block:: hy
=> (ap-pipe 3 (+ it 1) (/ 5 it))
1.25
=> (ap-pipe [4 5 6 7] (list (rest it)) (len it))
3
.. _ap-compose:
ap-compose
=========
Usage ``(ap-compose form1 form2 ...)``
Returns a function which applies several forms in series from left to right. The special variable ``ìt`` in each form is replaced by the result of the previous form.
.. code-block:: hy
=> (def op (ap-compose (+ it 1) (* it 3)))
=> (op 2)
9

View File

@ -109,3 +109,15 @@
`(let [[acc ~initial-value]]
(ap-each ~lst (setv acc ~form))
acc)))
(defmacro ap-pipe [var &rest forms]
"Pushes a value through several forms.
(Anaphoric version of -> and ->>)"
(if (empty? forms) var
`(ap-pipe (let [[it ~var]] ~(first forms)) ~@(rest forms))))
(defmacro ap-compose [&rest forms]
"Returns a function which is the composition of several forms."
`(fn [var] (ap-pipe var ~@forms)))

View File

@ -103,3 +103,13 @@
(assert-equal (ap-reduce (+ acc " on " it) ["Hy" "meth"])
"Hy on meth")
(assert-equal (ap-reduce (+ acc it) [] 1) 1))
(defn test-ap-pipe []
"NATIVE: testing anaphoric pipe"
(assert-equal (ap-pipe 2 (+ it 1) (* it 3)) 9)
(assert-equal (ap-pipe [4 5 6 7] (list (rest it)) (len it)) 3))
(defn test-ap-compose []
"NATIVE: testing anaphoric compose"
(assert-equal ((ap-compose (+ it 1) (* it 3)) 2) 9)
(assert-equal ((ap-compose (list (rest it)) (len it)) [4 5 6 7]) 3))