/var/log/messages

Feb 3, 2019 - 1 minute read - Comments - programming

プログラミング Elixir (15)

なんとなく parse は酷い感がアレ。とは言え色々面倒なのでこのまま進めます。

parse で出てきたリストを eval します。実装が以下。

  def eval([head|tail]) do
    _eval(head, tail)
  end

  defp _eval(num, [?+|tail]) do
    _eval_plus(num, tail)
  end
  defp _eval_plus(num, [head|tail]) do
    num + head
  end
  defp _eval(num, [?-|tail]) do
    _eval_minus(num, tail)
  end
  defp _eval_minus(num, [head|tail]) do
    num - head
  end
  defp _eval(num, [?*|tail]) do
    _eval_mul(num, tail)
  end
  defp _eval_mul(num, [head|tail]) do
    num * head
  end
  defp _eval(num, [?/|tail]) do
    _eval_div(num, tail)
  end
  defp _eval_div(num, [head|tail]) do
    num / head
  end

動作確認。

iex(12)> Parse.eval('{+-')
168

あるいは以下?

iex(13)> Parse.eval(Parse.parse('2 * 2'))
4
iex(14)> Parse.eval(Parse.parse('4 / 2'))
2.0
iex(15)> Parse.eval(Parse.parse('100 - 50'))
50

タイプが面倒なので apply をでっちあげてみるなど。

  def apply(str) do
    eval(parse(str))
  end

動作確認。

iex(16)> Parse.apply('2 * 2')
4
iex(17)> Parse.apply('4 / 2')
2.0
iex(18)> Parse.apply('100 - 50')
50

次はバイナリ、らしい。

Stanford Nlp プログラミング Elixir (16)

comments powered by Disqus