exploring article on Continuation Monad while learning Scala 3.
I understood the whole article and basically rewrote code into Scala 3 - except this single tricky goto
function:
{-# LANGUAGE ScopedTypeVariables #-}
import qualified Control.Monad.Trans.Cont as C
goto = C.callCC $ \out -> let fn = out fn
in return fn
this part utilizes Haskell's feature of recursive value definition - see let fn = out fn
.
Question: is it possible to have Scala expressing smth similar to such a recursive definition like let fn = out fn
? If not, how such thing can be replaced? I made some research, and learned that some particular cases can be represented by recursive use of lazy "Streams" (for ex when we can define lazy stream of ints recursively). Also i've learned this may be related to topic of "fixed points" which i explore at the moment...
PS. My question is about recursive definition representation. But if your are interested in my definitions of some types those are below (note, that my Inc
is what they call Cont
in their article):
type Cont[X, R] = X => R
case class Inc[A, R](runCont: Cont[A, R] => R) {
def map[B](fn: A => B): Inc[B, R] = {
val c = (out: B => R) => runCont(a => out(fn(a)))
Inc(c)
}
def flatMap[B](fn: A => Inc[B, R]): Inc[B, R] = {
val c = (out: B => R) => runCont(a => fn(a).runCont(out))
Inc(c)
}
}
object Inc {
def return_[A, R](a: A) = {
val c = (out: A => R) => out(a)
Inc(c)
}
def callCC[A, B, R](fn: (A => Inc[B, R]) => Inc[A, R]): Inc[A, R] = {
val c = (out: Cont[A, R]) => fn(a => Inc(_ => out(a))).runCont(out)
Inc(c)
}
}