Created
February 27, 2016 08:36
-
-
Save s3itz/c3fb58246bb8ba09063e to your computer and use it in GitHub Desktop.
This file contains 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
defmodule Parse do | |
def calculate(expression) do | |
{ left, rest } = Enum.split_while(expression, &(!(&1 in '+-*/'))) | |
[ op | right ] = rest | |
{ result, _ } = Code.eval_quoted { :erlang.list_to_atom([op]), [], | |
[value(left), value(right)] } | |
result | |
end | |
defp value(digits) do | |
digits |> to_string |> String.strip |> :erlang.binary_to_integer | |
end | |
end | |
IO.inspect Parse.calculate('123+123') | |
IO.inspect Parse.calculate(' 123 + 123 ') | |
IO.inspect Parse.calculate('12 * 12') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment