Skip to content

Commit

Permalink
Handling composed functors
Browse files Browse the repository at this point in the history
  • Loading branch information
turion committed Sep 28, 2024
1 parent ace722d commit cdcef02
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion automaton/src/Data/Stream.hs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module Data.Stream where

-- base
import Control.Applicative (Alternative (..), Applicative (..), liftA2)
import Control.Arrow ((>>>))
import Control.Monad ((<$!>), forM)
import Data.Bifunctor (bimap)
import Data.Function ((&))
Expand All @@ -18,7 +19,7 @@ import Prelude hiding (Applicative (..))

-- transformers
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE, withExceptT)
import Control.Monad.Trans.Except (ExceptT (..), runExceptT, throwE, withExceptT)

-- mmorph
import Control.Monad.Morph (MFunctor (hoist))
Expand Down Expand Up @@ -460,3 +461,30 @@ runListS StreamT {state, step} = StreamT
let flatResults = concat results
return $ Result (resultState <$> flatResults) (output <$> flatResults)
}

-- FIXME maybe rewrite with Iso somehow?
handleCompose :: (Functor f, Monad m, Monad composed) => (forall s . s -> f s) -> (forall x . composed x -> m (f x)) -> (forall x . m (f x) -> composed x) -> StreamT composed a -> StreamT m (f a)
handleCompose pure_ uncompose compose StreamT {state, step} = StreamT
{state = pure_ state
, step = \s -> do
results <- uncompose $ do
states <- compose $ pure s
step states
return $! Result (fmap resultState results) (fmap output results)
}


-- FIXME all these should go to a separate module
handleExceptT :: Monad m => StreamT (ExceptT e m) a -> StreamT m (Either e a)
handleExceptT = handleCompose pure runExceptT $ ExceptT

-- FIXME handleMaybeT


snapshot :: Functor m => StreamT m a -> StreamT m (m a)
snapshot StreamT {state, step} = StreamT
{ state
, step = \s ->
let result = step s
in flip Result (output <$> result) . resultState <$> result
}

0 comments on commit cdcef02

Please sign in to comment.