version | 3.0.1 |
license | MIT |
native-modules | False |
elm-version | 0.18.0 <= v < 0.19.0 |
Tag | 3.0.1 |
Committed At | 2016-11-15 07:32:03 UTC |
elm-lang/core | 5.0.0 <= v < 6.0.0 | 5.1.1 |
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 List
s.
Transducers can be used to combine processing operations in a way that allows processing to be done more efficiently.
When using List.map
, it is more efficient to compose multiple functions and then map the list with the composed function than to map the list with each function independently because the list will only be traversed once. Similarly, transducers can be used to process List
s more efficiently, but it is not limited to mapping operations. filter
, take
, drop
, and any other transducer can be efficiently composed.
import List as L
import Transducer as T exposing ((>>>))
slowMapChain = [1, 2, 3] |> L.map ((+) 10) |> L.map toString
fastMapChain = [1, 2, 3] |> L.map ((+) 10 >> toString)
slowChain = [1, 2, 3] |> L.filter ((/=) 2) |> L.map toString
fastChain = [1, 2, 3] |> T.transduceList (T.filter ((/=) 2) >>> T.map toString)
Transducers can be reused with many different data types. List
, Array
, Set
, Dict
are supported by this library, and you can define your own transducer processes to work with other data types.
You can also define transducer processes that convert between types (for example, transducing from a List
into a Set
).
import Maybe
import String
import Transducer as T exposing ((>>>))
parseValidInts =
T.map String.toInt
>>> T.map toMaybe
>>> T.filter ((/=) Nothing)
>>> T.map (Maybe.withDefault 0)
exampleList : List Int
exampleList = T.transduceList parseValidInts ["123", "-34", "35.0", "SDF", "7"]
exampleConvert : Set Int
exampleConvert = T.transduce List.foldr Set.insert Set.empty parseValidInts ["123", "-34", "35.0", "SDF", "7"]
Reducer
type to be a -> r -> r
instead of r -> a -> r