Skip to content

Instantly share code, notes, and snippets.

@s3itz
Created February 27, 2016 08:36
Show Gist options
  • Save s3itz/c3fb58246bb8ba09063e to your computer and use it in GitHub Desktop.
Save s3itz/c3fb58246bb8ba09063e to your computer and use it in GitHub Desktop.
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