scalafunctional-programmingfunctortrampolines

Trampoline as a Functor


I'm trying to demonstrate a Trampoline[+A] as a Functor (i.e., provides map[B](f: A = >B)). I understand the classic implementation of the Trampoline as a Monad as described in Stackless Scala.
However, is there a way to implement the map function (and not flatMap) with only Done and More subclasses of Trampoline, or do i need to add the Flatmap subclass also?


Solution

  • You can't cause Trampoline represents a computational process. Functor gives you a map function, which can only transform you final value, but to spawn a new computation is a job of a Monads, which in some way abstracts over the computation process, with a flatMap operation (although i definetly prefer Haskell bind name, cause it's better denotes the actual semantics of the operation). So with functors you can't chain different computation pieces together, e.g in scalaz Trampoline is an alias for a Free Monad which defines map like this:

    def map[B](f: A => B): Free[S, B] =
        flatMap(a => Return(f(a)))
    

    As you can see it only transforms a value, but doesn't attach a new step, what you want to achieve with Trampolines.