on ffca3ac help sign in
87 lines 2.4 kB history raw
1-- |
2-- Module : Streamly.Internal.Data.Stream.Transform
3-- Copyright : (c) 2017 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : experimental
7-- Portability : GHC
8--
9module Streamly.Internal.Data.Stream.Transform
10 (
11 filter
12 , foldFilter
13 , map
14 , mapM
15 )
16where
18import Streamly.Internal.Data.Fold.Type (Fold)
19import Streamly.Internal.Data.Stream.Type (Stream)
21import qualified Streamly.Internal.Data.Stream.Type as Stream
22import qualified Streamly.Internal.Data.Stream.StreamD.Transform as StreamD
24import Prelude hiding (map, mapM, filter)
26--
27-- $setup
28-- >>> :m
29-- >>> import qualified Streamly.Internal.Data.Fold as Fold
30-- >>> import qualified Streamly.Data.Unfold as Unfold
31-- >>> import qualified Streamly.Internal.Data.Stream as Stream
33------------------------------------------------------------------------------
34-- Transformation by Mapping
35------------------------------------------------------------------------------
37-- |
38-- >> mapM f = Stream.sequence . Stream.map f
39--
40-- Apply a monadic function to each element of the stream and replace it with
41-- the output of the resulting action.
42--
43-- >>> s = Stream.unfold Unfold.fromList ["a", "b", "c"]
44-- >>> Stream.fold Fold.drain $ Stream.mapM putStr s
45-- abc
46--
47-- /Pre-release/
48--
49{-# INLINE mapM #-}
50mapM :: Monad m => (a -> m b) -> Stream m a -> Stream m b
51mapM f = Stream.fromStreamD . StreamD.mapM f . Stream.toStreamD
53-- |
54-- >>> map = fmap
55--
56-- Same as 'fmap'.
57--
58-- >>> s = Stream.unfold Unfold.fromList [1,2,3]
59-- >>> Stream.fold Fold.toList $ Stream.map (+1) s
60-- [2,3,4]
61--
62-- /Pre-release/
63--
64{-# INLINE map #-}
65map :: Monad m => (a -> b) -> Stream m a -> Stream m b
66map f = mapM (return . f)
68-- | Include only those elements that pass a predicate.
69--
70{-# INLINE filter #-}
71filter :: Monad m => (a -> Bool) -> Stream m a -> Stream m a
72filter p = Stream.fromStreamD . StreamD.filter p . Stream.toStreamD
74-- | Use a filtering fold on a stream.
75--
76-- >>> :{
77-- Stream.fold Fold.sum
78-- $ Stream.foldFilter (Fold.maybe (\x -> if x > 5 then Just x else Nothing))
79-- $ Stream.unfold Unfold.fromList [1..10]
80-- :}
81--40
82--
83-- /Pre-release/
84--
85{-# INLINE foldFilter #-}
86foldFilter :: Monad m => Fold m a (Maybe b) -> Stream m a -> Stream m b
87foldFilter p = Stream.fromStreamD . StreamD.foldFilter p . Stream.toStreamD