Created
December 19, 2017 06:19
-
-
Save yasuabe/b38caf105591b61126db1d96fcd6b12a to your computer and use it in GitHub Desktop.
by writer monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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