Last active
August 29, 2023 12:26
-
-
Save aaylward/237089d32206163587b5f1275117af34 to your computer and use it in GitHub Desktop.
gleam rulez
This file contains hidden or 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
pub type Pizza { | |
Margherita | |
Caprese | |
Formaggio | |
ExtraSauce(Pizza) | |
ExtraToppings(Pizza) | |
} | |
fn pizza_price_helper(pizza: Pizza, acc: Int) -> Int { | |
case pizza { | |
Margherita -> 7 + acc | |
Caprese -> 9 + acc | |
Formaggio -> 10 + acc | |
ExtraSauce(p) -> pizza_price_helper(p, 1 + acc) | |
ExtraToppings(p) -> pizza_price_helper(p, 2 + acc) | |
} | |
} | |
pub fn pizza_price(pizza: Pizza) -> Int { | |
pizza | |
|> pizza_price_helper(0) | |
} | |
type SumAndCount { | |
SumAndCount(sum: Int, count: Int) | |
} | |
fn reduce(xs: List(a), fun: fn(b, a) -> b, acc: b) -> b { | |
case xs { | |
[] -> acc | |
[x, ..rest] -> reduce(rest, fun, fun(acc, x)) | |
} | |
} | |
fn sum_and_count(a: SumAndCount, b: Pizza) -> SumAndCount { | |
SumAndCount(sum: a.sum + pizza_price(b), count: a.count + 1) | |
} | |
fn compute_total(x: SumAndCount) -> Int { | |
case x { | |
SumAndCount(sum: s, count: 1) -> s + 3 | |
SumAndCount(sum: s, count: 2) -> s + 2 | |
SumAndCount(sum: s, count: _) -> s | |
} | |
} | |
pub fn order_price(order: List(Pizza)) -> Int { | |
order | |
|> reduce(sum_and_count, SumAndCount(sum: 0, count: 0)) | |
|> compute_total() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment