Created
February 10, 2021 21:49
-
-
Save mgryszko/122a72cc70015937c2818258061ec3ad to your computer and use it in GitHub Desktop.
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
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