Skip to content

Instantly share code, notes, and snippets.

@HomMarkHunt
Last active December 7, 2017 11:40
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 HomMarkHunt/741728d162b198e166b09b169da6c036 to your computer and use it in GitHub Desktop.
Save HomMarkHunt/741728d162b198e166b09b169da6c036 to your computer and use it in GitHub Desktop.
fp-scala-2
// 関数型ソリューション
class Cafe {
def buyCoffee(cc: CreditCard): (Coffee, Charge) = {
val cup = new Coffee()
(cup, cup.price) // charge作成を切り離す
}
}
/**
* CreditCardとAmountを持つ.
* 他のChargeをまとめるconbineをもつ.
*
* @param cc
* @param amount
*/
case class Charge(cc: CreditCard, amount: Double) {
def combine(other: Charge): Charge =
if (cc == other.cc)
Charge(cc, amount + other.amount) // 他のchargeをまとめる
else
throw new Exception("Otherチャージがないよ")
}
def buyCoffees(cc: CreditCard, n: Int): (List[Coffee], Charge) = {
val purchases: List[(Coffee, Charge)] = List.fill(n)(buyCoffee(cc)) // List.fill(n)(x)よくわからん, xのコピーをn個含んだListを作成する
val (coffees, charges) = purchases.unzip // unzipでpairを分解
(coffees, charges.reduce((c1, c2) => c1.combine(c2)))
}
// 同じカードへのChargeを一つにまとめる
def coalesce(charges: List[Charge]): List[Charge] = {
charges.groupBy(_.cc).values.map(_.reduce(_ combine _)).toList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment