Skip to content

Instantly share code, notes, and snippets.

@GMadorell
Created September 30, 2018 18:52
Show Gist options
  • Save GMadorell/e373688e3e85feb3510e4fc12274ab47 to your computer and use it in GitHub Desktop.
Save GMadorell/e373688e3e85feb3510e4fc12274ab47 to your computer and use it in GitHub Desktop.
Software Crafters Barcelona 2018 - Open Space Monadic Refactor Workshop
import cats.{Id, Monad}
import cats.implicits._
object AccumulateConventional extends App {
trait Console {
def write(text: String): Unit
def read(): String
}
def accumulateUntilNegativeNumber(counter: Int = 0)(console: Console): Unit = {
console.write("Input a number pls")
val input = console.read()
val inputAsNumber = input.toInt
if (inputAsNumber < 0) console.write(counter.toString)
else accumulateUntilNegativeNumber(counter + inputAsNumber)(console)
}
val stdConsole = new Console {
override def write(text: String): Unit = println(text)
override def read(): String = scala.io.StdIn.readLine()
}
val fixFirstParameter: Console => Unit = accumulateUntilNegativeNumber(0)
fixFirstParameter(stdConsole)
}
object AccumulateMonadic extends App {
trait Console[P[_]] {
def write(text: String): P[Unit]
def read(): P[String]
}
def accumulateUntilNegativeNumber[P[_]](
counter: Int = 0
)(implicit console: Console[P], M: Monad[P]): P[Unit] =
for {
_ <- console.write("Input a number pls")
input <- console.read()
inputAsNumber = input.toInt
_ <- if (inputAsNumber < 0) console.write(counter.toString)
else accumulateUntilNegativeNumber(counter + inputAsNumber)
} yield ()
object Console {
implicit object IdConsole extends Console[Id] {
override def write(text: String): Unit = println(text)
override def read(): String = scala.io.StdIn.readLine()
}
}
case class IOState(toBeRead: List[String], written: List[String])
type ConsoleTransformer[T] = IOState => (IOState, T)
object IOState{
implicit object ConsoleTransformerIO extends Console[ConsoleTransformer]{
def write(text: String): ConsoleTransformer[Unit] = ???
def read(): ConsoleTransformer[String] = {
case IOState(head :: tail, written) =>
(IOState(tail : List[String], written : List[String]), head : String)
}
}
accumulateUntilNegativeNumber(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment