Skip to content

Instantly share code, notes, and snippets.

@cb372
Last active April 11, 2017 13:44
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 cb372/b9cac3c0b327d1c998f6362b52ac4ae3 to your computer and use it in GitHub Desktop.
Save cb372/b9cac3c0b327d1c998f6362b52ac4ae3 to your computer and use it in GitHub Desktop.
Welcome to the Ammonite Repl 0.8.2
(Scala 2.12.1 Java 1.8.0_121)
@ import $ivy.`org.typelevel::cats:0.9.0`, cats._, cats.implicits._
import $ivy.$ , cats._, cats.implicits._
@
@ trait Maths[F[_]] {
def int(i: Int): F[Int]
def add(l: F[Int], r: F[Int]): F[Int]
}
defined trait Maths
@
@ trait Logging[F[_]] {
def info(s: String): F[Unit]
}
defined trait Logging
@
@ class MyProgram[F[_]](alg: Maths[F] with Logging[F])(implicit M: Monad[F]) {
import alg._
def addTwoNumbers(a: Int, b: Int): F[Int] =
for {
_ <- info(s"Adding $a and $b")
result <- add(int(a), int(b))
} yield result
}
defined class MyProgram
@
@ val interp = new Maths[Id] with Logging[Id] {
def int(a:Int) = a
def add(a: Id[Int], b: Id[Int]) = a + b
def info(msg: String) = println(msg)
}
interp: AnyRef with Maths[Id] with Logging[Id] = $sess.cmd4$$anon$1@60ce75d0
@
@ val prog = new MyProgram[Id](interp)
prog: MyProgram[Id] = $sess.cmd3$MyProgram@27353d1c
@
@ prog.addTwoNumbers(3, 4)
Adding 3 and 4
res6: Id[Int] = 7
Welcome to the Ammonite Repl 0.8.2
(Scala 2.12.1 Java 1.8.0_121)
@ import $ivy.`org.typelevel::cats:0.9.0`, cats._, cats.implicits._
import $ivy.$ , cats._, cats.implicits._
@
@ trait Maths[F[_]] {
def int(i: Int): F[Int]
def add(l: F[Int], r: F[Int]): F[Int]
}
defined trait Maths
@
@ trait Logging[F[_]] {
def info(s: String): F[Unit]
}
defined trait Logging
@
@ object MathsStuff {
// don't even need the Monad bound in this case, but you get the idea
def addTwoNumbers[F[_]: Monad](a: Int, b: Int)(implicit alg: Maths[F]): F[Int] = {
import alg._
add(int(a), int(b))
}
}
defined object MathsStuff
@
@ object LogStuff {
def writeSomeThings[F[_]: Monad](implicit alg: Logging[F]): F[Unit] = {
import alg._
for {
_ <- info("hello")
_ <- info("world")
} yield ()
}
}
defined object LogStuff
@
@ object MyProg {
def addAndLog[F[_]: Monad](implicit alg: Maths[F] with Logging[F]): F[Int] = {
for {
_ <- LogStuff.writeSomeThings[F]
result <- MathsStuff.addTwoNumbers[F](3, 4)
} yield result
}
}
defined object MyProg
@
@ implicit val interp = new Maths[Id] with Logging[Id] {
def int(a:Int) = a
def add(a: Id[Int], b: Id[Int]) = a + b
def info(msg: String) = println(msg)
}
interp: AnyRef with Maths[Id] with Logging[Id] = $sess.cmd7$$anon$1@550e427a
@
@ MyProg.addAndLog[Id]
hello
world
res8: Id[Int] = 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment