A transducer is a composable way of processing a series of values.
Many basic transducers correspond to functions you may be familiar with for
processing Lists.
import Maybe
import String
import Transducer exposing (..)
parseValidInts =
map String.toInt
|> composeWith (map toMaybe)
|> composeWith (filter ((/=) Nothing))
|> composeWith (map (Maybe.withDefault 0))
exampleList : List Int
exampleList =
transduceList parseValidInts [ "123", "-34", "35.0", "SDF", "7" ]A transducer an init value for it's internal state, a step function that
transforms a Reducer into a Reducer of a new type, and a complete function that
transforms a Reducer into a function collapsing the internal state.
When defining transducers, the type parameter r should be left free.
A fold is function that takes a Reducer, an initial value, and input source, and returns a final value.
Apply a function to every value.
transduceList (map sqrt) [ 1, 4, 9 ] == [ 1, 2, 3 ]Keep only values that satisfy the predicate.
transduceList (filter isEven) (List.range 1 6) == [ 2, 4, 6 ]Take the first n values.
transduceList (take 2) [ 1, 2, 3, 4 ] == [ 1, 2 ]Drop the first n values.
transduceList (drop 2) [ 1, 2, 3, 4 ] == [ 3, 4 ]Map a given function onto a list and flatten the results.
transduceList (concatMap (\x -> [ x, x + 10 ])) [ 1, 2 ] == [ 1, 10, 2, 20 ]Drop values that repeat the previous value.
transduceList dedupe [ 1, 1, 2, 2, 1 ] == [ 1, 2, 1 ]Group a series of values into Lists of size n.
transduceList (partition 2) [ 1, 2, 3, 4, 5 ] == [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]Compose two transducers.
firstOperation
|> composeWith secondOperationApply a transducer.
Apply a Transducer to a List, producing a List.
transduceList t xs == transduce List.foldr (::) [] t xsApply a Transducer to a Set, producing a Set.
transduceSet t xs =
transduce Set.foldr Set.insert Set.empty t xsApply a Transducer to an Array, producing an Array.
transduceArray t xs =
transduce Array.foldl Array.push Array.empty t xs
A reducer is a function taking an input and a value and produces a new value.