Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Created January 31, 2013 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpolecat/4679827 to your computer and use it in GitHub Desktop.
Save tpolecat/4679827 to your computer and use it in GitHub Desktop.
import language.higherKinds
import java.sql.Connection
import scalaz.{ Monad, StateT, Functor, State }
import scalaz.State._
import scalaz.MonadState._
import scalaz.std.tuple._
import scalaz.syntax.monad._
import scalaz.syntax.std.tuple._
import scalaz.effect.IO
import scalaz.effect.IO._
object Jed {
class ConnectionWrapper(c: Connection) {
def setAutoCommit(autoCommit: Boolean): IO[Unit] = IO(c.setAutoCommit(autoCommit))
def getAutoCommit: IO[Boolean] = IO(c.getAutoCommit)
}
// State[Connection,A] becomes StateT[IO,ConnectionWrapper,A]
def action: StateT[IO, ConnectionWrapper, Boolean] =
for {
w <- initT[IO, ConnectionWrapper]
c <- liftM(w.getAutoCommit)
} yield c
val conn: Connection = ???
val ioAction = action.eval(new ConnectionWrapper(conn))
val result = ioAction.unsafePerformIO
// Some combinators and lifted operations for StateT
def lift[M[+_]: Monad, S, A](f: State[S, A]) = StateT[M, S, A](f(_).pure[M])
def liftM[M[+_]: Functor, S, A](f: M[A]) = StateT[M, S, A](s => f.map((s, _)))
def initT[M[+_]: Monad, S] = lift[M, S, S](init[S])
def modifyT[M[+_]: Monad, S](f: S => S) = lift[M, S, Unit](modify[S](f))
def putT[M[+_]: Monad, S](s: S) = lift[M, S, Unit](put(s))
def getsT[M[+_]: Monad, S, A](f: S => A) = lift[M, S, A](gets(f))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment