Elixir 練習問題 StringsAndBinaries-4

defmodule Calculater do
  def calculate(charlist) do
    parse(charlist)
    |> calc
  end

  defp parse(charlist) do
    tokenize(charlist, [[]])
    |> _parse
  end

  defp tokenize([], result) do
    Enum.reverse(result)
  end
  defp tokenize([32|tail], result) do
    tokenize(tail, [[] | result])
  end
  defp tokenize([head|tail], [cur|rest]) do
    tokenize(tail, [cur ++ [head] | rest])
  end

  defp _parse([opnd1, op, opnd2]) do
    num1 = number(opnd1, 0)
    num2 = number(opnd2, 0)
    {op, num1, num2}
  end

  defp number([], value) do
    value
  end
  defp number([digit|tail], value) do
    number(tail, value * 10 + digit - ?0)
  end

  defp calc({'+', n1, n2}), do: n1 + n2
  defp calc({'-', n1, n2}), do: n1 - n2
  defp calc({'*', n1, n2}), do: n1 * n2
  defp calc({'/', n1, n2}), do: n1 / n2
end


IO.puts Calculater.calculate('123 + 27')
IO.puts Calculater.calculate('123 - 23')
IO.puts Calculater.calculate('100 * 2')
IO.puts Calculater.calculate('100 / 5')
^o^ > elixir practice_11_4.exs
150
100
200
20.0