Elixir 練習問題 ListsAndRecursion-8

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 が最初に追加されちゃってるのがちょっと気に入らないけど、まあいいか。

Elixir 練習問題 ListsAndRecursion-7

以前に作った span 関数と内包表記を使って 2 から n までの素数。

defmodule MyList do
  def span(from, to) when from == to, do: [to]
  def span(from, to),                 do: [from | span(from + 1, to)]

  def primes(n) do
    for x <- span(2, n), is_prime(x), do: x
  end

  defp is_prime(2), do: true
  defp is_prime(3), do: true
  defp is_prime(n) do
    m = div(n, 2)
    Enum.all?(Enum.map(span(2, m), fn x -> rem(n, x) != 0 end))
  end
end
^o^ > iex practice_10_3.exs
Eshell V8.0  (abort with ^G)
Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyList.primes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]