iT邦幫忙

2022 iThome 鐵人賽

DAY 9
0

While preparing to bake cookies for your friends, you have found that you have to convert some of the measurements used in the recipe. Being only familiar with the metric system, you need to come up with a way to convert common US baking measurements to milliliters (mL) for your own ease.

Being a talented programmer in training, you decide to use milliliters as a transition unit to facilitate the conversion from any unit listed to any other (even itself).

1. Get the numeric component from a volume-pair

Implement the KitchenCalculator.get_volume/1 function. Given a volume-pair tuple, it should return just the numeric component.

2. Convert the volume-pair to milliliters

Implement the KitchenCalculator.to_milliliter/1 function. Given a volume-pair tuple, it should convert the volume to milliliters using the conversion chart.

Use multiple function clauses and pattern matching to create the functions for each unit. The atoms used to denote each unit are: :cup, :fluid_ounce, :teaspoon, :tablespoon, :milliliter. Return the result of the conversion wrapped in a tuple.

3. Convert the milliliter volume-pair to another unit

Implement the KitchenCalculator.from_milliliter/2 function. Given a volume-pair tuple and the desired unit, it should convert the volume to the desired unit using the conversion chart.

Use multiple function clauses and pattern matching to create the functions for each unit. The atoms used to denote each unit are: :cup, :fluid_ounce, :teaspoon, :tablespoon, :milliliter

4. Convert from any unit to any unit

Implement the KitchenCalculator.convert/2 function. Given a volume-pair tuple and the desired unit, it should convert the given volume to the desired unit.


https://exercism.org/tracks/elixir/exercises/kitchen-calculator

defmodule KitchenCalculator do
  def get_volume(volume_pair), do: elem volume_pair, 1

  def to_milliliter({:cup, value}), do: {:milliliter, value * 240}

  def to_milliliter({:fluid_ounce, value}), do: {:milliliter, value * 30}

  def to_milliliter({:teaspoon, value}), do: {:milliliter, value * 5}

  def to_milliliter({:tablespoon, value}), do: {:milliliter, value * 15}

  def to_milliliter({:milliliter, _} = volume_pair), do: volume_pair

  def from_milliliter({_, value}, :cup), do: {:cup, value / 240}

  def from_milliliter({_, value}, :fluid_ounce), do: {:fluid_ounce, value / 30}

  def from_milliliter({_, value}, :teaspoon), do: {:teaspoon, value / 5}

  def from_milliliter({_, value}, :tablespoon), do: {:tablespoon, value / 15}

  def from_milliliter(volume_pair, :milliliter), do: volume_pair

  def convert(volume_pair, unit) do
    volume_pair
    |> to_milliliter
    |> from_milliliter(unit)
  end
end

上一篇
八.Multiple Clause Functions
下一篇
十. Recursion
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言