Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # given an input like the following "five minus ten plus four plus ten times minus six"
- # create a function that will perform the calculation (5 - 10 + 4 + 10 * - 6)
- # only needs to accept numbers -10..10
- # only needs to account for multiplication and addition/subtraction
- # needs to follow proper order of operations
- defmodule Calculator do
- def operation(:plus, a, b) do
- a + b
- end
- def operation(:minus, a, b) do
- a - b
- end
- def operation(:times, a, b) do
- a * b
- end
- def parse(tokens) do
- tokens = parse(tokens, [], [:times])
- tokens = parse(tokens, [], [:plus, :minus])
- tokens
- end
- def scan(tokens) do
- case tokens do
- [:minus, a, operator, :minus, b | rest] ->
- {:expr, -a, operator, -b, rest}
- [a, operator, :minus, b | rest] ->
- {:expr, a, operator, -b, rest}
- [:minus, a, operator, b | rest] ->
- {:expr, -a, operator, b, rest}
- [a, operator, b | rest] ->
- {:expr, a, operator, b, rest}
- [:minus, a | rest] ->
- {:term, -a, rest}
- [a | rest] ->
- {:term, a, rest}
- [] ->
- :end
- end
- end
- def parse(tokens, accumulator, pass) do
- case scan(tokens) do
- {:expr, a, operator, b, rest} ->
- if operator in pass do
- result = operation(operator, a, b)
- parse([result | rest], accumulator, pass)
- else
- parse(tl(tokens), accumulator ++ [hd(tokens)], pass)
- end
- {:term, a, rest} ->
- parse(rest, accumulator ++ [a], pass)
- :end ->
- accumulator
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement