Created
February 26, 2016 09:36
-
-
Save s3itz/ef0caf9ac0b18bad2695 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 Eval do | |
def calculate(str), do: _calculate(str) | |
defp _calculate(str) do | |
{op, i} = find(str) | |
list1 = Enum.slice(str, 0..i-1) | |
list2 = Enum.slice(str, i+2..length(str)) | |
_calculate(op, list1, list2) | |
end | |
defp _calculate(?+, list1, list2), do: number(list1) + number(list2) | |
defp _calculate(?-, list1, list2), do: number(list1) - number(list2) | |
defp _calculate(?*, list1, list2), do: number(list1) * number(list2) | |
defp _calculate(?/, list1, list2), do: number(list1) / number(list2) | |
defp find(str), do: _find(str, 0) | |
defp _find([], _), do: raise "No operator" | |
defp _find([ h | t ], i) do | |
if h in '+-*/' do | |
{h, i} | |
else | |
_find(t, i+1) | |
end | |
end | |
def number(str), do: _number(str, 0) | |
defp _number([], value), do: value | |
defp _number([ ?\s ], value), do: value | |
defp _number([ digit | tail ], value) | |
when digit in '0123456789' do | |
_number(tail, value*10 + digit - ?0) | |
end | |
defp _number([ non_digit | _ ], _), do: raise "Invalid digit #{[non_digit]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment