I'm learning Scala by translating a Haskell function to Scala. I have a monad transformer stack containing the StateMonad
type TI a = ...
One function using this monad transformer stack is:
fresh :: TI Int
fresh = do n <- get
put (n + 1)
return n
Since this function only depends on the State monad I may also change the type to:
fresh :: (MonadState Int m) => m Int
How does this translate to Scala? In Scala, I use a monad transformer stack composing the state and the identity monad:
type TI[A] = StateT[Id, scala.Int, A]
The fresh function in Scala looks like this:
def fresh:TI[Ty] = for {
counter <- get[scala.Int]
_ <- put[scala.Int] (counter + 1)
} yield {
TyVar(counter)
}
How do I rewrite the type signature in Scala in such a way that in only depends on the State monad and not on the whole monad transformer stack?
Scalaz also provides a
MonadState
type class, although the limitations of Scala's type inference means it's much less elegant. You could write the following, for example:And then for example the following:
Note that the first type parameter for
MonadState
needs to have holes for both the state and the value, so you'll need to adjust yourTI
if you want to use this approach—fresh[TI]
won't work as is.