3 ms·
An interesting take on transducers is that they're just functions that return lists transducer : a -> List b with one additional caveat: they can contain
by dwohnitmok 9y ago
An interesting take on transducers is that they're just functions that return lists
transducer : a -> List b
with one additional caveat: they can contain internal mutable state.
For example the map transducer just takes in a function and returns a modified form of that function that wraps the result in a single element list. The filter transducer takes in a predicate and returns a modified form of that predicate that returns an empty list or single element list of the argument when the predicate evaluates to false or true respectively.
The take transducer is what requires state (and indeed it is implemented with mutable state in Clojure in the form of an internal counter). That means no reusing stateful transduced reducers otherwise you'll find it's already "exhausted." In this case just do the same thing as the map transducer on the identity function until the internal counter hits the number of elements specified.
Composing the transducers becomes just flatmapping/mapcatting one over the result of the previous one (Kleisli composition for those familiar with Haskell).
Running the transducers on an actual structure requires an actual reducing function and consists of first passing an element to the transducer, then reducing over the generated list with the reducing function, and offering the reduced result as the beginning accumulator for the next element that gets passed into the transducer.
See https://stackoverflow.com/questions/26653829/how-is-a-transducer-different-from-a-partially-applied-function https://stackoverflow.com/questions/26653829/how-is-a-transd... for where I first learned about the fundamentals behind this.