ProgrammingElixir1.6-MyTurns/ListsAndRecursion-8.exs

51 lines
1.9 KiB
Elixir
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# The Pragmatic Bookshelf has offices in Texas (TX) and North Carolina (NC), so we have to charge sales tax on orders shipped to these states.
# The rates can be expressed as a keyword list (I wish it were that simple.…):
# tax_rates = [ NC: 0.075, TX: 0.08 ]
# Heres a list of orders:
# orders = [
# [ id: 123, ship_to: :NC, net_amount: 100.00 ],
# [ id: 124, ship_to: :OK, net_amount: 35.50 ],
# [ id: 125, ship_to: :TX, net_amount: 24.00 ],
# [ id: 126, ship_to: :TX, net_amount: 44.80 ],
# [ id: 127, ship_to: :NC, net_amount: 25.00 ],
# [ id: 128, ship_to: :MA, net_amount: 10.00 ],
# [ id: 129, ship_to: :CA, net_amount: 102.00 ],
# [ id: 130, ship_to: :NC, net_amount: 50.00 ] ]
# Write a function that takes both lists and returns a copy of the orders, but with an extra field, total_amount, which is the net plus sales tax.
# If a shipment is not to NC or TX, theres no tax applied.
tax_rates = [ NC: 0.075, TX: 0.08 ]
orders= [
[ id: 123, ship_to: :NC, net_amount: 100.00 ],
[ id: 124, ship_to: :OK, net_amount: 35.50 ],
[ id: 125, ship_to: :TX, net_amount: 24.00 ],
[ id: 126, ship_to: :TX, net_amount: 44.80 ],
[ id: 127, ship_to: :NC, net_amount: 25.00 ],
[ id: 128, ship_to: :MA, net_amount: 10.00 ],
[ id: 129, ship_to: :CA, net_amount: 102.00 ],
[ id: 130, ship_to: :NC, net_amount: 50.00 ]
]
defmodule Calculator do
def process(orders, tax_rates) do
for order <- orders, do: order ++ [ total_amount: total_amount(order, tax_rates) ]
end
defp total_amount(order, tax_rates) do
tax_rate = tax_rates[order[:ship_to]]
if tax_rate == nil do
order[:net_amount]
else
order[:net_amount] + order[:net_amount] * tax_rate
end
end
end
IO.inspect Calculator.process(orders, tax_rates)