Skip to content

Instantly share code, notes, and snippets.

@mgryszko
Created February 10, 2021 21:49
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 mgryszko/122a72cc70015937c2818258061ec3ad to your computer and use it in GitHub Desktop.
Save mgryszko/122a72cc70015937c2818258061ec3ad to your computer and use it in GitHub Desktop.
import cats.kernel.Monoid
import cats.syntax.monoid._
type Quantity = Int
type Pricer[A] = Quantity => (Quantity, A)
def total[A: Monoid](pricings: List[(Quantity, List[Pricer[A]])]): A = {
pricings.foldLeft(Monoid[A].empty) { case (grandTotal, (quantity, pricers)) =>
grandTotal |+| total(quantity, pricers)
}
}
private def total[A: Monoid](quantity: Quantity, pricers: List[Pricer[A]]): A = {
val (_, total) = pricers.foldLeft((quantity, Monoid[A].empty)) {
case ((quantity, total), pricer) =>
val (remainingQuantity, amount) = pricer(quantity)
(remainingQuantity, total |+| amount)
}
total
}
def priceByTier[A: Monoid](quantityPerTier: Quantity, tierPrice: A): Pricer[A] = { quantity =>
val tiers = quantity / quantityPerTier
(quantity % quantityPerTier, tierPrice.combineN(tiers))
}
def priceByUnit[A: Monoid](unitPrice: A): Pricer[A] = { quantity =>
(0, unitPrice.combineN(quantity))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment