Skip to content

Instantly share code, notes, and snippets.

@runarorama
Created October 17, 2011 05:39
Show Gist options
  • Save runarorama/1292001 to your computer and use it in GitHub Desktop.
Save runarorama/1292001 to your computer and use it in GitHub Desktop.
Regional database connections
object Regional {
case class IOM[M, A](unwrap: IO[A])
case class Q[M](c: Connection)
def iomMonad[M]: Monad[({type λ[α] = IOM[M, α]})#λ] =
new Monad[({type f[a] = IOM[M, a]})#f] {
def pure[A](a: => A) = IOM[M, A](a.point[IO])
def bind[A, B](m: IOM[M, A], f: A => IOM[M, B]) =
IOM(m.unwrap >>= (x => f(x).unwrap))
}
def executeQuery[M](q: Q[M], s: String): IOM[M, ResultSet] =
IOM(io { q.c.executeQuery(s) })
def withConnection[M, A](u: url, f: Q[M] => IOM[M, A]): IOM[M, A] =
IOM(openConnection(u).bracket(closeConnection, c => f(Q(c)).unwrap))
def runIOM(x: Forall[({type λ[μ] = IOM[μ, A]})#λ]): IO[A] =
x.unwrap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment