Skip to content

Commit

Permalink
Add example of higher-order effect handler (DynamicReader)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lysxia authored and tomjaguarpaw committed Nov 22, 2024
1 parent b8054b1 commit eec720c
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions bluefin-internal/src/Bluefin/Internal/Examples.hs
Original file line number Diff line number Diff line change
Expand Up @@ -1021,3 +1021,42 @@ rethrowIOExample = runEff $ \io -> do
effIO io $ putStrLn $ case r of
Left e -> "Caught IOException:\n" ++ show e
Right contents -> contents

data DynamicReader r e = DynamicReader
{ askLRImpl :: forall e'. Eff (e' :& e) r,
localLRImpl :: forall e' a. (r -> r) -> Eff e' a -> Eff (e' :& e) a
}

instance Handle (DynamicReader r) where
mapHandle h =
DynamicReader
{ askLRImpl = useImplUnder (askLRImpl h),
localLRImpl = \f k -> useImplUnder (localLRImpl h f k)
}

askLR ::
(e :> es) =>
DynamicReader r e ->
Eff es r
askLR c = makeOp (askLRImpl (mapHandle c))

localLR ::
(e :> es) =>
DynamicReader r e ->
(r -> r) ->
Eff es a ->
Eff es a
localLR c f m = makeOp (localLRImpl (mapHandle c) f m)

runDynamicReader ::
r ->
(forall e. DynamicReader r e -> Eff (e :& es) a) ->
Eff es a
runDynamicReader r k =
runReader r $ \h -> do
useImplIn
k
DynamicReader
{ askLRImpl = ask h,
localLRImpl = \f k' -> makeOp (local h f (useImpl k'))
}

0 comments on commit eec720c

Please sign in to comment.