mapM package:streamly
mapM f = sequence . map f
Apply a monadic function to each element of the stream and replace it
with the output of the resulting action.
>>> drain $ Stream.mapM putStr $ Stream.fromList ["a", "b", "c"]
abc
>>> :{
drain $ Stream.replicateM 10 (return 1)
& (fromSerial . Stream.mapM (x -> threadDelay 1000000 >> print x))
:}
1
...
1
> drain $ Stream.replicateM 10 (return 1)
& (fromAsync . Stream.mapM (x -> threadDelay 1000000 >> print x))
Concurrent (do not use with fromParallel on infinite
streams)
mapM_ = Stream.drain . Stream.mapM
Apply a monadic action to each element of the stream and discard the
output of the action. This is not really a pure transformation
operation but a transformation followed by fold.
Map a
Maybe returning function to a stream, filter out the
Nothing elements, and return a stream of values extracted from
Just.
Equivalent to:
mapMaybe f = Stream.map fromJust . Stream.filter isJust . Stream.map f
Like
mapMaybe but maps a monadic function.
Equivalent to:
mapMaybeM f = Stream.map fromJust . Stream.filter isJust . Stream.mapM f
Concurrent (do not use with fromParallel on infinite
streams)
Definition:
>>> parMapM modifier f = Stream.parConcatMap modifier (Stream.fromEffect . f)
For example, the following finishes in 3 seconds (as opposed to 6
seconds) because all actions run in parallel. Even though results are
available out of order they are ordered due to the config option:
>>> f x = delay x >> return x
>>> Stream.fold Fold.toList $ Stream.parMapM (Stream.ordered True) f $ Stream.fromList [3,2,1]
1 sec
2 sec
3 sec
[3,2,1]
Map a stream producing monadic function on each element of the stream
and then flatten the results into a single stream. Since the stream
generation function is monadic, unlike
concatMap, it can
produce an effect at the beginning of each iteration of the inner
loop.
Like
concatMapWith but carries a state which can be used to
share information across multiple steps of concat.
concatSmapMWith combine f initial = concatMapWith combine id . smapM f initial
Pre-release
Like iterateMap but carries a state in the stream generation
function. This can be used to traverse graph like structures, we can
remember the visited nodes in the state to avoid cycles.
Note that a combination of iterateMap and usingState
can also be used to traverse graphs. However, this function provides a
more localized state instead of using a global state.
See also: mfix
Pre-release
Like
rollingMap but with an effectful map function.
Pre-release
A stateful
mapM, equivalent to a left scan, more like
mapAccumL. Hopefully, this is a better alternative to
scan.
Separation of state from the output makes it easier to think in terms
of a shared state, and also makes it easier to keep the state fully
strict and the output lazy.
See also:
scanlM'
Pre-release