Creating a signature of a type independent of a specific monad transformer stack (Scala)

I am learning Scala, translating the Haskell function to Scala. I have a monad transformer stack containing StateMonad

type TI a = ... 

One of the features using this monad transformer stack is:

fresh :: TI Int
fresh = do n <- get
           put (n + 1)
           return n

Since this function depends only on the state monad, I can also change the type:

fresh :: (MonadState Int m) => m Int

How to translate this to Scala? In Scala, I use a monad transformer stack, making up a state and a monodal copy:

type TI[A] = StateT[Id, scala.Int, A]

A new feature in Scala is as follows:

def fresh:TI[Ty] = for {
  counter <- get[scala.Int]
  _ <- put[scala.Int] (counter + 1)
} yield {
  TyVar(counter)
}

How to rewrite the type signature in Scala so that it depends only on the state monad, and not on the entire stack of the monad transformer?

+3
source share
1

Scalaz MonadState, Scala , . , :

import scalaz._, Scalaz._

def fresh[F[_, _]](implicit m: MonadState[F, Int]): F[Int, Int] = for {
  counter <- m.get
  _       <- m.put(counter + 1)
} yield counter

, , :

scala> fresh[State]
res6: scalaz.State[Int,Int] = scalaz.IndexedStateT$$anon$10@6517b62

scala> type OptionState[s, a] = StateT[Option, s, a]
defined type alias OptionState

scala> fresh[OptionState]
res7: OptionState[Int,Int] = scalaz.IndexedStateT$$anon$10@43740ba6

, MonadState , , TI, - fresh[TI] .

+4

Source: https://habr.com/ru/post/1533350/


All Articles