Skip to content

Instantly share code, notes, and snippets.

@fuadsaud
Last active March 19, 2016 20:10
Show Gist options
  • Save fuadsaud/a995c86fb4674f80cf0b to your computer and use it in GitHub Desktop.
Save fuadsaud/a995c86fb4674f80cf0b to your computer and use it in GitHub Desktop.
module Checkout where
import Data.List
type Price = Integer
type Product = Char
type Cart = [Product]
type Rule = Cart -> Price
total :: Cart -> [Rule] -> Price
total cart rules = sum $ map ($ cart) rules
simplePrice :: Product -> Price -> Cart -> Price
simplePrice sku regularPrice = modPrice sku regularPrice 1 regularPrice
modPrice :: Product -> Price -> Price -> Price -> Cart -> Price
modPrice sku regularPrice quantity specialPrice cart = d * specialPrice + m * regularPrice
where
products = filter (== sku) cart
count = genericLength products
d = count `quot` quantity
m = count `mod` quantity
module CheckoutTest where
import Checkout
rules :: [Rule]
rules = [ modPrice 'A' 50 3 130,
modPrice 'B' 30 2 45,
simplePrice 'C' 20,
simplePrice 'D' 15 ]
calculateTotal :: Cart -> Price
calculateTotal = flip total rules
assertions :: Bool
assertions = all id [
0 == calculateTotal "",
50 == calculateTotal "A",
80 == calculateTotal "AB",
115 == calculateTotal "CDBA",
100 == calculateTotal "AA",
130 == calculateTotal "AAA",
180 == calculateTotal "AAAA",
230 == calculateTotal "AAAAA",
260 == calculateTotal "AAAAAA",
160 == calculateTotal "AAAB",
175 == calculateTotal"AAABB",
190 == calculateTotal"AAABBD",
190 == calculateTotal"DABABA"]
main :: IO ()
main = print assertions
@matiasleidemer
Copy link

wow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment