Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.61 KB | None | 0 0
  1. # given an input like the following "five minus ten plus four plus ten times minus six"
  2. # create a function that will perform the calculation (5 - 10 + 4 + 10 * - 6)
  3. # only needs to accept numbers -10..10
  4. # only needs to account for multiplication and addition/subtraction
  5. # needs to follow proper order of operations
  6.  
  7. defmodule Calculator do
  8.   def operation(:plus, a, b) do
  9.     a + b
  10.   end
  11.  
  12.   def operation(:minus, a, b) do
  13.     a - b
  14.   end
  15.  
  16.   def operation(:times, a, b) do
  17.     a * b
  18.   end
  19.  
  20.   def parse(tokens) do
  21.     tokens = parse(tokens, [], [:times])
  22.     tokens = parse(tokens, [], [:plus, :minus])
  23.     tokens
  24.   end
  25.  
  26.   def scan(tokens) do
  27.     case tokens do
  28.       [:minus, a, operator, :minus, b | rest] ->
  29.         {:expr, -a, operator, -b, rest}
  30.  
  31.       [a, operator, :minus, b | rest] ->
  32.         {:expr, a, operator, -b, rest}
  33.  
  34.       [:minus, a, operator, b | rest] ->
  35.         {:expr, -a, operator, b, rest}
  36.  
  37.       [a, operator, b | rest] ->
  38.         {:expr, a, operator, b, rest}
  39.  
  40.       [:minus, a | rest] ->
  41.         {:term, -a, rest}
  42.  
  43.       [a | rest] ->
  44.         {:term, a, rest}
  45.  
  46.       [] ->
  47.         :end
  48.     end
  49.   end
  50.  
  51.   def parse(tokens, accumulator, pass) do
  52.     case scan(tokens) do
  53.       {:expr, a, operator, b, rest} ->
  54.         if operator in pass do
  55.           result = operation(operator, a, b)
  56.           parse([result | rest], accumulator, pass)
  57.         else
  58.           parse(tl(tokens), accumulator ++ [hd(tokens)], pass)
  59.         end
  60.  
  61.       {:term, a, rest} ->
  62.         parse(rest, accumulator ++ [a], pass)
  63.  
  64.       :end ->
  65.         accumulator
  66.     end
  67.   end
  68. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement