I followed the talk given by Runar Bjarnason about free monads: http://functionaltalks.org/2014/11/23/runar-oli-bjarnason-free-monad/
I have the following piece of code from his initial example (I used the name Continuation instead of Bind and Box instead of F - I like them better for now) :
object TestFreeMonads
{
sealed trait Interact[A]
case class Ask(prompt: String) extends Interact[String]
case class Tell(msg: String) extends Interact[Unit]
sealed trait Free[Box[_], A] {
def flatMap[B](f: A => Free[Box, B]): Free[Box, B] =
this match {
case Return(a) => f(a)
case Continuation(v, cont ) => Continuation(v, cont andThen (_ flatMap f) )
// The following line does not compile: missing parameter type for expanded function ((<x$1: error>) => cont(x$1).flatMap(f))
// case Continuation(v, cont ) => Continuation(v, cont(_).flatMap(f) )
// This line does compile:
// case Continuation(v, cont ) => Continuation[Box, Any, B](v, cont(_).flatMap(f) )
}
def map[B](f: A => B): Free[Box, B] = flatMap(a => Return(f(a)))
}
case class Return[Box[_], A](a: A) extends Free[Box, A]
case class Continuation[Box[_], I, A](v: Box[I], cont: I => Free[Box, A]) extends Free[Box, A]
def lift[Box[_], A](v: Box[A]): Free[Box, A] = Continuation(v, (a: A) => Return(a))
implicit def liftInteract[A](v: Interact[A]) : Free[Interact, A] = lift(v)
def prog: Free[Interact, Unit] = {
for {
first <- Ask("First Name")
last <- Ask("Last Name")
_ <- Tell(s"Hello, $first $last")
} yield ()
}
}
I don't understand why this line compiles: case Continuation(v, cont ) => Continuation(v, cont andThen (_ flatMap f) ) but not this one: case Continuation(v, cont ) => Continuation(v, cont(_).flatMap(f) ).
The third line case Continuation(v, cont ) => Continuation[Box, Any, B](v, cont(_).flatMap(f) ) compiles as well but it is kind of verbose and I used Any as value for the I type parameter which I think it is questionable. Ideally I should declare somehow the type of v and use it, but it doesn't seem possible.
Ultimately v has the type I but it is kind of under the hood.
I used scala 2.13.1:
...
scalaVersion := "2.13.1"
scalacOptions += "-feature"
scalacOptions += "-language:implicitConversions"
...