Created
December 19, 2017 06:22
-
-
Save yasuabe/7c173a6ce908802cab3ad05266a29d56 to your computer and use it in GitHub Desktop.
by state 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.State | |
case class CashRegister(total: Int) { | |
def addCash(toAdd: Int) = CashRegister(total + toAdd) | |
} | |
type Purchase = CashRegister => CashRegister | |
def makePurchase(amount: Int): Purchase = (r: CashRegister) => { | |
println("Purchase in amount: " + amount) | |
r addCash amount | |
} | |
type PurchaseHistory = Vector[Purchase] | |
def execute(p: Purchase): State[(PurchaseHistory, CashRegister), Unit] = | |
State { case (h, r) => ((h :+ p, p(r)), ()) } | |
// test ------------------------------------------------------------------- | |
val p1 = makePurchase(100) | |
val p2 = makePurchase(50) | |
def program = for { | |
_ <- execute(p1) | |
_ <- execute(p2) | |
} yield () | |
val (history, total1) = program.runS((Vector.empty, CashRegister(0))).value | |
// 再実行 | |
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