Search code examples
clojureclojurescripttransducer

Idiom for transducing over an atom?


What is the idiomatic way to apply transducers to an atom's value?

This seems to do the job, but I'm unsure of correctness (and style ^^).

 (let [xf1 (map inc) 
       xf2 (map #(+ % 2)) 
       xf #(vec (eduction (comp xf2 xf1) %)) 
       a (atom [1 2 3])] 
   (swap! a xf))
 ;=> [4 5 6]

Solution

  • (let [xf1 (map inc) 
          xf2 (map #(* % 2)) 
          foo #(into [] (comp xf2 xf1) %) 
          a (atom [1 2 3])] 
      (swap! a foo))
    ;; => [3 5 7]
    

    There are two things you need to take note.

    1. comp in transducers works the opposite order as normal applications. That is, xf2 is applied prior to xf1. For each element, it is doubled then incremented.
    2. eduction returns a sequence, so it's not the same type as your original value in the atom.