Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - How does this work when `comp` goes from right to left?

The documentation for comp states that it starts with the rightmost function, applies the arguments to it, then gives the result to the next function and so on. Hence here the numbers are added first then str is applied to the integer 16:

((comp str +) 8 8) ;;=> "16"

This code is from example 7 in the core.async webinar:

mouse (events->chan js/window EventType.MOUSEMOVE
       (chan 1 
       (comp (map mouse-loc->vec) 
             (filter (fn [[_ y]] (zero? (mod y 5)))))))

Here a stream of mouse events are the arguments. They are first converted into a pair (tuple 2 vector) and then these pairs are filtered. The map function (which happens to be a transducer) needs to receive the mouse event before the filter function, and obviously that is what is actually happening because this code works. So why is the first operation (the map function) not the rightmost function argument to comp?

Answer In the video at 25:30 Rich Hickey says "transducers ruin comp or something like that" - after that he explains the issue. Thanks @nblumoe

like image 300
Chris Murphy Avatar asked Nov 25 '25 13:11

Chris Murphy


1 Answers

Here is a snippet from the transducer documentation, explaining the behavior:

Composition of the transformer runs right-to-left but builds a transformation stack that is applied left-to-right

http://clojure.org/transducers (see "Defining Transformations with transducers")

like image 78
Nils Blum-Oeste Avatar answered Nov 28 '25 11:11

Nils Blum-Oeste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!