Last active
May 22, 2016 19:50
-
-
Save rogeralsing/8f968f8fc6ccbf0896456e0c4c586c4a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run(), do: eval('5 * 5 + 2-2 + 10 *20*0') |> IO.inspect | |
def eval(input), do: _tokenize(input, []) |> _eval1([]) |> _eval2() | |
defp _tokenize([32 | input], result), do: _tokenize input, result | |
defp _tokenize([char | input], [{:num, num} | result]) when char >= ?0 and char <= ?9, do: _tokenize input, [{:num, num * 10 + (char - ?0)} | result] | |
defp _tokenize([char | input], result) when char >= ?0 and char <= ?9, do: _tokenize input, [{:num, (char - ?0)} | result] | |
defp _tokenize([?* | input], result), do: _tokenize input, [:mul | result] | |
defp _tokenize([?/ | input], result), do: _tokenize input, [:div | result] | |
defp _tokenize([?+ | input], result), do: _tokenize input, [:add | result] | |
defp _tokenize([?- | input], result), do: _tokenize input, [:sub | result] | |
defp _tokenize([], result), do: result |> Enum.reverse() | |
defp _eval1([{:num,left},:mul,{:num,right} | tail], result), do: _eval1 [{:num, left * right} | tail], result | |
defp _eval1([{:num,left},:div,{:num,right} | tail], result), do: _eval1 [{:num, left / right} | tail], result | |
defp _eval1([any | tail], result), do: _eval1 tail, [any | result] | |
defp _eval1([], result), do: result |> Enum.reverse() | |
defp _eval2([{:num,left},:add,{:num,right} | tail]), do: _eval2 [{:num, left + right} | tail] | |
defp _eval2([{:num,left},:sub,{:num,right} | tail]), do: _eval2 [{:num, left - right} | tail] | |
defp _eval2([{:num,value}]), do: value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment