State Transformers

What is State transformer and STRef trying to achieve?

Let us define the ST monad (in scalaz). In the simplified form it is,

case class World[A]()

case class ST[S, A](f: World[S] => (World[S], A)) {
  def apply(s: World[S]) = ..
  def flatMap[B](g: A => ST[S, B]): ST[S, B] = ...
  def map[B](g: A => B): ST[S, B] = ....
}
x
def returnST[S, A](a: => A): ST[S, A] = ...

STRef

STRef is a mutable variable (updatable location in the state capabale of holding a value) that’s used only with in the context of ST Monad. And that is, ST[S, STRef[S, A]] `

case class STRef[S, A](a: A) { private var value: A = a

// only path-way to access the value (it will be encapsulated in ST) def read: ST[S, A] = returnST(value)

// associate the new value `a` to this reference. // write mutates the object in place. def write(a: A): ST[S, STRef[S, A]] = ...

// modifies the value at this reference, that is `read` and then `write` def mod[B](f: A => A): ST[S, STRef[S, A]] = ... }

def newVar(a: => A) = returnST(STRef(a))

A simplified version is [here] (https://github.com/afsalthaj/supaku-sukara/blob/master/src/main/scala/com/thaj/functionalprogramming/exercises/part1/PureStatefulAPIGeneric.scala#L243)

Characteristics of STRef in a ST

Taking STRef out of ST ? No….

So what are we trying to achieve?

Exposing STRef by any chance should lead to compile time error, or in other words no freedom to compose STRef by itself without a State thread.

Examples

trait Forall[P[_]] { def apply[A]: P[A] }

def runST[A](f: Forall[({type F[S] = ST[S, A]})#F]): A = ... 

Refer to [my project]((https://github.com/afsalthaj/supaku-sukara/blob/master/src/main/scala/com/thaj/functionalprogramming/exercises/part1/PureStatefulAPIGeneric.scala#L243) for further examples, where we try to run the actions in many ways resulting in compile time errors.