-
-
Save nielsbom/0d689e00d927cc057ad7c5595d7e8f06 to your computer and use it in GitHub Desktop.
Programming Elixir 1.6: exercise StringsAndBinaries-4
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
ExUnit.start() | |
IO.puts( | |
"------------------------------------------RESTART------------------------------------------" | |
) | |
defmodule This do | |
# takes a single-quoted string of the form number [+-*/] number and returns | |
# the result of the calculation. The individual numbers do not have leading | |
# plus or minus signs. | |
# calculate('123 + 27') # => 150 | |
def calculate(command) do | |
[arg1, operator, arg2] = | |
command | |
|> List.to_string() | |
|> String.split() | |
|> Enum.zip([ | |
&String.to_integer/1, | |
&String.to_atom/1, | |
&String.to_integer/1 | |
]) | |
|> Enum.map(fn {item, func} -> func.(item) end) | |
apply(:erlang, operator, [arg1, arg2]) | |
end | |
end | |
defmodule AssertionTest do | |
use ExUnit.Case, async: true | |
test "calculate" do | |
assert This.calculate('1 + 2') == 3 | |
assert This.calculate('1 + 0') == 1 | |
assert This.calculate('1 - 2') == -1 | |
assert This.calculate('1 * 2') == 2 | |
assert This.calculate('9 / 3') == 3 | |
assert This.calculate('9 / 3') == 3 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment