Backtrace Handling in Monads

I’m running into a bit of a tricky issue surrounding backtraces and monads, specifically a reader monad.
Due to the inversion of control in bind, all the backtraces contain only frames involving bind, which leads to some less than helpful traces:

        Raised at Core__Semantics.dispatch_rigid_hcom.go in file "src/core/Semantics.ml", line 1552, characters 6-67
        Called from Basis__Monad.MonadReaderResult.bind in file "src/basis/Monad.ml", line 169, characters 10-15
        Called from Basis__Monad.MonadReaderResult.bind in file "src/basis/Monad.ml", line 169, characters 10-15
... about 100 lines more of the same stuff

I know lwt has a clever trick involving a PPX + using the reraise primitive, but I was wondering if anyone else has any less invasive tricks that I could use to somehow massage these stack traces. Any help is appreciated!

For context, here’s the implementation of bind

  let bind m k env =
    match m env with
    | Ok a -> k a env
    | Error exn -> Error exn
1 Like

As far as I know effect handlers are intended to be the OCaml answer to this. If this is experimental code it might be worth your while to port it to OCaml Multicore (or OCaml 5+trunk) and use effects.