Skip to content

Instantly share code, notes, and snippets.

@ihainan
Last active September 18, 2017 09:13
Show Gist options
  • Save ihainan/a5b89bb75c6f2d00483bacd4e97ac618 to your computer and use it in GitHub Desktop.
Save ihainan/a5b89bb75c6f2d00483bacd4e97ac618 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"source": "// A coffee example\n\ndef c1_1_2() {\n case class CreditCard(id: String)\n \n case class Charge(cc: CreditCard, amount: Double) {\n def combine(other: Charge): Charge = \n if (cc == other.cc) Charge(cc, amount + other. amount)\n else throw new Exception(\"Can't combine charges to different cards\")\n \n def doCharge() {\n println(s\"\"\"Charge $amount dollars to credit card \"${cc.id}\".\"\"\")\n }\n }\n \n case class Coffee(price: Int)\n \n class Cafe {\n def buyCoffee(cc: CreditCard): (Coffee, Charge) = {\n val cup = new Coffee(10)\n (cup, Charge(cc, cup.price))\n }\n \n def buyCoffees(cc: CreditCard, n: Int): (List[Coffee], Charge) = {\n var purchars: List[(Coffee, Charge)] = List.fill(n)(buyCoffee(cc))\n val (coffees, charges) = purchars.unzip\n (coffees, charges.reduce((c1, c2) => c1.combine(c2)))\n }\n \n def coalesce(charges: List[Charge]): List[Charge] = {\n charges.groupBy(_.cc).values.map(_.reduce(_ combine _)).toList\n }\n }\n \n val cafe = new Cafe()\n val aliceCreditCard = CreditCard(\"Alice\")\n val bobCreditCard = CreditCard(\"Bob\")\n val (_, firstCharge) = cafe.buyCoffees(aliceCreditCard, 10)\n val (_, secondCharge) = cafe.buyCoffees(bobCreditCard, 20)\n val (_, thirdCharge) = cafe.buyCoffees(aliceCreditCard, 30)\n val combinedCharges = cafe.coalesce(List(firstCharge, secondCharge, thirdCharge))\n println(combinedCharges)\n \n combinedCharges.foreach(_.doCharge)\n}\n\nc1_1_2()",
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"text": "List(Charge(CreditCard(Bob),200.0), Charge(CreditCard(Alice),400.0))\nCharge 200.0 dollars to credit card \"Bob\".\nCharge 400.0 dollars to credit card \"Alice\".\n",
"name": "stdout"
}
],
"metadata": {}
},
{
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": [],
"metadata": {
"collapsed": true
}
}
],
"nbformat": 4,
"nbformat_minor": 1,
"metadata": {
"kernelspec": {
"language": "scala",
"display_name": "Scala 2.11 with Spark 2.1",
"name": "scala-spark21"
},
"language_info": {
"pygments_lexer": "scala",
"file_extension": ".scala",
"codemirror_mode": "text/x-scala",
"version": "2.11.8",
"mimetype": "text/x-scala",
"name": "scala"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment