0

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)
  }
}
Max
  • 1,741
  • 3
  • 23
  • 40
  • 1
    Scala is eagerly evaluated, so some things need `lazy val` (sometimes creatively used). Type aliases cannot be recursive, but trait/classes can. Add to it different type inference in Scala than it is in Haskell and you'll see why a lot of data types from Haskell are represented as traits/classes, even if they are just wrappers around functions. For cont you can take a look at [`ContT` implementation from Cats](https://github.com/typelevel/cats/blob/c74f0a7cf58429808ffbfc31dd8d9d7eed9a3132/core/src/main/scala/cats/data/ContT.scala) to see how it was done. – Mateusz Kubuszok Feb 26 '23 at 17:07
  • 1
    Mateusz, hi. an offtopic comment - are you an author of https://kubuszok.com/compiled/kinds-of-types-in-scala/ ? i've read it last week while learning scala types, wonderful article btw – Max Feb 26 '23 at 17:23

0 Answers0