defmodule Order do def sales_tax(orders, tax_rates) do orders |> Enum.map(fn o -> {o, tax_rate(o, tax_rates)} end) |> Enum.map(fn {o, tax_rate} -> Keyword.put(o, :total_amount, add_tax(o, tax_rate)) end) end defp tax_rate(order, rates) do ship_to = Keyword.get(order, :ship_to) Keyword.get(rates, ship_to, 0.0) end defp add_tax(order, tax_rate) do Keyword.get(order, :net_amount) * (1.0 + tax_rate) end end 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: 100.00 ], [ id: 130, ship_to: :NC, net_amount: 50.00 ] ] Order.sales_tax(orders, tax_rates) |> Enum.each(&IO.inspect/1)
^o^ > elixir practice_10_4.exs [total_amount: 107.5, id: 123, ship_to: :NC, net_amount: 100.0] [total_amount: 35.5, id: 124, ship_to: :OK, net_amount: 35.5] [total_amount: 25.92, id: 125, ship_to: :TX, net_amount: 24.0] [total_amount: 48.384, id: 126, ship_to: :TX, net_amount: 44.8] [total_amount: 26.875, id: 127, ship_to: :NC, net_amount: 25.0] [total_amount: 10.0, id: 128, ship_to: :MA, net_amount: 10.0] [total_amount: 100.0, id: 129, ship_to: :CA, net_amount: 100.0] [total_amount: 53.75, id: 130, ship_to: :NC, net_amount: 50.0]
total_amount が最初に追加されちゃってるのがちょっと気に入らないけど、まあいいか。