|
| 1 | +module Effectful.Coroutine |
| 2 | + ( -- * Effect |
| 3 | + Coroutine(..) |
| 4 | + , Input |
| 5 | + , Output |
| 6 | + |
| 7 | + -- ** Handlers |
| 8 | + , runCoroutine |
| 9 | + , runInputConst |
| 10 | + , runOutputArray |
| 11 | + , runOutputList |
| 12 | + |
| 13 | + -- ** Operations |
| 14 | + , yield |
| 15 | + , input |
| 16 | + , output |
| 17 | + ) where |
| 18 | + |
| 19 | +import Data.Bifunctor |
| 20 | +import Data.Kind |
| 21 | + |
| 22 | +import Effectful |
| 23 | +import Effectful.Dispatch.Dynamic |
| 24 | +import Effectful.Input.Const qualified as IC |
| 25 | +import Effectful.Output.Array qualified as OA |
| 26 | +import Effectful.State.Static.Local qualified as S |
| 27 | + |
| 28 | +data Coroutine (a :: Type) (b :: Type) :: Effect where |
| 29 | + Yield :: a -> Coroutine a b m b |
| 30 | + |
| 31 | +type instance DispatchOf (Coroutine i o) = Dynamic |
| 32 | + |
| 33 | +type Input i = Coroutine () i |
| 34 | + |
| 35 | +type Output o = Coroutine o () |
| 36 | + |
| 37 | +---------------------------------------- |
| 38 | +-- Handlers |
| 39 | + |
| 40 | +-- | Run the 'Coroutine' effect via a given action. |
| 41 | +runCoroutine |
| 42 | + :: HasCallStack |
| 43 | + => (a -> Eff es b) |
| 44 | + -- ^ The action. |
| 45 | + -> Eff (Coroutine a b : es) a |
| 46 | + -> Eff es a |
| 47 | +runCoroutine f = interpret_ $ \case |
| 48 | + Yield a -> f a |
| 49 | + |
| 50 | +-- | Run the 'Coroutine' effect via "Effectful.Input.Const". |
| 51 | +runInputConst |
| 52 | + :: HasCallStack |
| 53 | + => i |
| 54 | + -- ^ The input. |
| 55 | + -> Eff (Input i : es) a |
| 56 | + -> Eff es a |
| 57 | +runInputConst i = reinterpret_ (IC.runInput i) $ \case |
| 58 | + Yield () -> IC.input |
| 59 | + |
| 60 | +-- | Run the 'Coroutine' effect via "Effectful.Output.Array". |
| 61 | +runOutputArray |
| 62 | + :: HasCallStack |
| 63 | + => Eff (Output o : es) a |
| 64 | + -- ^ . |
| 65 | + -> Eff es (a, OA.Array o) |
| 66 | +runOutputArray = reinterpret_ OA.runOutput $ \case |
| 67 | + Yield o -> OA.output o |
| 68 | + |
| 69 | +runOutputList |
| 70 | + :: HasCallStack |
| 71 | + => Eff (Output o : es) a |
| 72 | + -- ^ . |
| 73 | + -> Eff es (a, [o]) |
| 74 | +runOutputList = reinterpret_ setup $ \case |
| 75 | + Yield o -> S.modify (o :) |
| 76 | + where |
| 77 | + setup = fmap (second reverse) . S.runState [] |
| 78 | + |
| 79 | +---------------------------------------- |
| 80 | +-- Operations |
| 81 | + |
| 82 | +-- | Yield to the handler with the given value. |
| 83 | +yield :: forall b a es. (HasCallStack, Coroutine a b :> es) => a -> Eff es b |
| 84 | +yield = send . Yield |
| 85 | + |
| 86 | +-- | Request the value from the handler. |
| 87 | +input :: (HasCallStack, Coroutine () i :> es) => Eff es i |
| 88 | +input = send $ Yield () |
| 89 | + |
| 90 | +-- | Pass the value to the handler. |
| 91 | +output :: (HasCallStack, Coroutine o () :> es) => o -> Eff es () |
| 92 | +output = send . Yield |
0 commit comments