Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created December 19, 2017 06:19
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 yasuabe/b38caf105591b61126db1d96fcd6b12a to your computer and use it in GitHub Desktop.
Save yasuabe/b38caf105591b61126db1d96fcd6b12a to your computer and use it in GitHub Desktop.
by writer monad
import cats.data.Writer
import cats.instances.vector._
import cats.syntax.writer._
case class CashRegister(total: Int) {
def addCash(toAdd: Int) = CashRegister(total + toAdd)
}
type Purchase = CashRegister => CashRegister
def makePurchase(amount: Int): Purchase = (r: CashRegister) => {
println(s"Purchase in amount: $amount")
r addCash amount
}
type PurchaseHistory = Vector[Purchase]
def execute(purchase: Purchase)
: CashRegister => Writer[PurchaseHistory, CashRegister] =
register => purchase(register).writer(Vector(purchase))
// test -------------------------------------------------------------------
val p1 = makePurchase(100)
val p2 = makePurchase(50)
def program(r0: CashRegister) = for {
r1 <- execute(p1)(r0)
r2 <- execute(p2)(r1)
} yield r2
val (history, total1) = program(CashRegister(0)).run
// 再実行
history.foldLeft(CashRegister(10))((acc, p) => p(acc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment