chicken-hackers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Chicken-hackers] Thrush operator


From: Moritz Heidkamp
Subject: [Chicken-hackers] Thrush operator
Date: Tue, 14 Feb 2012 21:27:42 +0100

Hello Chickeneers,

find attached a suggested addition to miscmacros: the thrush operator
family. Apparently it stems from Raymond Smullyan's book on
combinatorial logic "To Mock a Mockingbird", which I haven't read
(yet). I've first learned about it through Clojure and have found it
quite nice for increasing the readability of chained calls. See Debasish
Ghosh's post [1] about it for some background.

As a practical example, consider this code:

  (write (fold + 0
               (map (lambda (i) (* 2 i)) 
                    (iota 10))))

Using the thrush operator it can be written like this:

  (->> (iota 10)
       (map (lambda (i) (* 2 i)))
       (fold + 0)
       (write))

which basically expands to the expression above, i.e. it inserts each
expression as the last argument of the following expression. I find it
much easier to read though since the order of evaluation is the order of
appearance in the code. I like to think of it like `let*' as opposed to
nested `lambda':

  ((lambda (x) ((lambda (y) ((lambda (z) (+ x y z)) 3)) 2)) 1)

versus:
  
  (let* ((x 1) (y 2) (z 3)) (+ x y z))

Much easier to track what's going on there as stuff that belongs
together is visually close to each other. 

There's also `->' which inserts each expression as the first argument of
the following one. The difference:

  (->> 10 (- 3)) ; => -7
  (-> 10 (- 3))  ; => 7

For kicks and fun I also added starred versions (`->*' and `->>*') which
are multi-value aware. Not sure how useful that is and I didn't want to
add it to the default macros to avoid the overhead. But it's good to
have them just for completeness sake!

I guess that's about it. I'm not sure if adding it to miscmacros is a
great idea, might as well just create a `thrush' egg. OTOH we have the
similar `doto' macro in there already. Comments?


Moritz

[1] http://debasishg.blogspot.com/2010/04/thrush-in-clojure.html

Attachment: miscmacros-thrush.patch
Description: Text Data


reply via email to

[Prev in Thread] Current Thread [Next in Thread]