on master help sign in
Add hoist and generally
02efa2cHarendra Kumar
src/Streamly/Internal/Data/Fold.hs+23
@@ -26,6 +26,9 @@ module Streamly.Internal.Data.Fold
26 -- * Fold Type
26 -- * Fold Type
27 Fold (..)
27 Fold (..)
28
28
29+ , hoist
30+ , generally
31+
29 -- , tail
32 -- , tail
30 -- , init
33 -- , init
31
34
@@ -180,6 +183,7 @@ module Streamly.Internal.Data.Fold
180where
183where
181
184
182import Control.Monad (void)
185import Control.Monad (void)
186+import Data.Functor.Identity (Identity(..))
183import Data.Map.Strict (Map)
187import Data.Map.Strict (Map)
184
188
185import Prelude
189import Prelude
@@ -244,6 +248,25 @@ mkFold = Fold
244mkFoldId :: Monad m => (b -> a -> m b) -> m b -> Fold m a b
248mkFoldId :: Monad m => (b -> a -> m b) -> m b -> Fold m a b
245mkFoldId step initial = Fold step initial return
249mkFoldId step initial = Fold step initial return
246
250
251+------------------------------------------------------------------------------
252+-- hoist
253+------------------------------------------------------------------------------
254+
255+-- | Change the underlying monad of a fold
256+--
257+-- /Internal/
258+hoist :: (forall x. m x -> n x) -> Fold m a b -> Fold n a b
259+hoist f (Fold step initial extract) =
260+ Fold (\x a -> f $ step x a) (f initial) (f . extract)
261+
262+-- | Adapt a pure fold to any monad
263+--
264+-- > generally = hoist (return . runIdentity)
265+--
266+-- /Internal/
267+generally :: Monad m => Fold Identity a b -> Fold m a b
268+generally = hoist (return . runIdentity)
269+
247------------------------------------------------------------------------------
270------------------------------------------------------------------------------
248-- Transformations on fold inputs
271-- Transformations on fold inputs
249------------------------------------------------------------------------------
272------------------------------------------------------------------------------