I am looking for a type that would allow me to imagine the context in which the code snippet is executed. For example:
def withinContext[R]: ((=> R) => R) = (inner) => { initializeSomeResource() try { inner } finally { releaseTheResource() } }
which can then be used simply as
withinContext { ... }
Or, if the inner block of code needs some information from the context, generalize it as
def withinContext[R]: ((Ctx => R) => R) = ...
Their use cases roughly correspond to Haskell bracket_ and bracket .
I could use the types (=> R) => R and (A => R) => R directly, but then I do not have utility functions to combine such context wrappers, so I wonder if there is something like that already exists in Scala ecosystem
Closes what I know, scala.util.control.Exception.Catch , which provides nice functions for building and merging Catch instances, but there seems to be no way to start any initialization before executing the inner block. In addition (this is not so important for my use case), it does not allow giving a parameter to internal calculation, as in the case (A => R) => R
Type (A => R) => R is a continuation of the monad corresponding to Haskell ContT r IO a , but I could not find an implementation of the continuation of the monad in any Scala standard (it may be hidden somewhere deep in Scalas where I missed it) .
scala continuations
Petr pudlรกk
source share