From 4205e58d7ea98096d2e7ca7e2a7ff750da66f514 Mon Sep 17 00:00:00 2001 From: Magnar Sveen Date: Sat, 20 Oct 2012 09:55:25 +0200 Subject: [PATCH] Add clojure threading macros, !-> and !->> --- bang.el | 23 +++++++++++++++++++++++ examples.el | 13 +++++++++++++ 2 files changed, 36 insertions(+) diff --git a/bang.el b/bang.el index b8879c1..81c2350 100644 --- a/bang.el +++ b/bang.el @@ -154,6 +154,29 @@ args first and then ARGS." `(closure (t) (&rest args) (apply ',fn (append args ',args)))) +(defmacro !-> (x &optional form &rest more) + "Threads the expr through the forms. Inserts X as the second +item in the first form, making a list of it if it is not a list +already. If there are more forms, inserts the first form as the +second item in second form, etc." + (cond + ((null form) x) + ((null more) (if (listp form) + `(,(car form) ,x ,@(cdr form)) + (list form x))) + (:else `(!-> (!-> ,x ,form) ,@more)))) + +(defmacro !->> (x form &rest more) + "Threads the expr through the forms. Inserts X as the last item +in the first form, making a list of it if it is not a list +already. If there are more forms, inserts the first form as the +last item in second form, etc." + (if (null more) + (if (listp form) + `(,(car form) ,@(cdr form) ,x) + (list form x)) + `(!->> (!->> ,x ,form) ,@more))) + (defun !distinct (list) "Return a new list with all duplicates removed. The test for equality is done with `equal', diff --git a/examples.el b/examples.el index a57af86..2fcd990 100644 --- a/examples.el +++ b/examples.el @@ -71,6 +71,19 @@ (funcall (!rpartial '- 5) 8) => 3 (funcall (!rpartial '- 5 2) 10) => 3) +(defexamples !-> + (!-> "Abc") => "Abc" + (!-> "Abc" (concat "def")) => "Abcdef" + (!-> "Abc" (concat "def") (concat "ghi")) => "Abcdefghi" + (!-> 5 square) => 25 + (!-> 5 (+ 3) square) => 64) + +(defexamples !->> + (!->> "Abc" (concat "def")) => "defAbc" + (!->> "Abc" (concat "def") (concat "ghi")) => "ghidefAbc" + (!->> 5 (- 8)) => 3 + (!->> 5 (- 3) square) => 4) + (defexamples !difference (!difference '() '()) => '() (!difference '(1 2 3) '(4 5 6)) => '(1 2 3)