Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add multiplication
However, the simple way in which expressions are evaluated have
to be changed since operator precedence is not taken into
consideration.
  • Loading branch information
dwayne committed Jul 9, 2019
1 parent d5ebef9 commit 848c4e3
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/Calculator.elm
Expand Up @@ -7,6 +7,15 @@ module Calculator exposing
)


-- TODO:
--
-- Respect operator precedence when evaluating expressions.
-- Yes. 1 + 2 * 3 = 1 + 6 = 7
-- No. 1 + 2 * 3 = 3 * 3 = 9 <---- This is current behaviour.
--
-- The CodePen example uses JavaScript's eval.


type Calculator
= Start
| Left Int
Expand All @@ -25,12 +34,14 @@ type Key
type Operator
= Plus
| Minus
| Times


type Expr
= Const Int
| Add Expr Expr
| Sub Expr Expr
| Mul Expr Expr


new : Calculator
Expand Down Expand Up @@ -128,6 +139,9 @@ eval expr =
Sub a b ->
(eval a) - (eval b)

Mul a b ->
(eval a) * (eval b)


operatorToExpr : Operator -> Expr -> Expr -> Expr
operatorToExpr op =
Expand All @@ -138,6 +152,9 @@ operatorToExpr op =
Minus ->
Sub

Times ->
Mul


type alias Display =
{ expr : String
Expand Down Expand Up @@ -192,6 +209,9 @@ exprToString expr =
Sub a b ->
(exprToString a) ++ "-" ++ (exprToString b)

Mul a b ->
(exprToString a) ++ "*" ++ (exprToString b)


operatorToString : Operator -> String
operatorToString op =
Expand All @@ -201,3 +221,6 @@ operatorToString op =

Minus ->
"-"

Times ->
"*"
2 changes: 1 addition & 1 deletion src/Main.elm
Expand Up @@ -75,7 +75,7 @@ viewCalculator calculator =
[ text "AC" ]
, button [ class "r0 c2", disabled True ]
[ text "÷" ]
, button [ class "r0 c3", disabled True ]
, button [ class "r0 c3", onClick (Clicked (Operator Times)) ]
[ text "×" ]
, button [ class "r1 c0", onClick (Clicked (Digit 7)) ]
[ text "7" ]
Expand Down
25 changes: 24 additions & 1 deletion tests/Test/Calculator.elm
Expand Up @@ -10,7 +10,9 @@ import Calculator exposing (Key(..), Operator(..))
suite : Test
suite =
describe "Calculator"
[ processSuite ]
[ processSuite
, operatorPrecedenceSuite
]


processSuite : Test
Expand Down Expand Up @@ -185,3 +187,24 @@ processSuite =
|> Expect.equal { expr = "12+3-4=11", output = "11" }
]
]


operatorPrecedenceSuite : Test
operatorPrecedenceSuite =
describe "operator precedence" <|
[ test "multiplication is done before addition" <|
\_ ->
let
calculator =
Calculator.new
|> Calculator.process (Digit 1)
|> Calculator.process (Operator Plus)
|> Calculator.process (Digit 2)
|> Calculator.process (Operator Times)
|> Calculator.process (Digit 3)
|> Calculator.process Equal
in
calculator
|> Calculator.toDisplay
|> Expect.equal { expr = "1+2*3=7", output = "7" }
]

0 comments on commit 848c4e3

Please sign in to comment.