Merge pull request #788 from nicolas-p/ap-pipe-ap-compose
Added ap-pipe and ap-compose macros
This commit is contained in:
commit
4642625378
1
AUTHORS
1
AUTHORS
@ -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>
|
||||
|
@ -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
|
||||
|
@ -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)))
|
||||
|
@ -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))
|
||||
|
Loading…
Reference in New Issue
Block a user