Last active
December 7, 2017 11:40
-
-
Save HomMarkHunt/741728d162b198e166b09b169da6c036 to your computer and use it in GitHub Desktop.
fp-scala-2
This file contains 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
// 関数型ソリューション | |
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