Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created December 19, 2017 06:22
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/7c173a6ce908802cab3ad05266a29d56 to your computer and use it in GitHub Desktop.
Save yasuabe/7c173a6ce908802cab3ad05266a29d56 to your computer and use it in GitHub Desktop.
by state monad
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