How to Build a Calculator

Calculator is a common tool for us to get the arithmetic expression’s result. In *NIX OS, once you type bc command, then you get into calculating environment. Feel free to input any legal arithmetic expressions.

bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.For details type `warranty'.
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 29 2018, 20:59:26)[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> 1 * 2 + 3 - 4 / 23>>>
  • Parse
  • Evaluate
  • Pratt parsing method
  • How to evaluate system

2 Environment

3 Implementation

Take simplicity into consideration, our calculator only supports integer number, excluding float or complex number. And supports add(+), minus(-), multiply(*), division(/) and power (^) operators. Parenthesizes to group expression is also supported.

  • Left subtree, including leaves 1 and 2 with operator +: It also can be considered as Expression and now it is InfixExpression.
  • The whole tree: It is still an Expression, even an InfixExpression. But this time, its left branch is another InfixExpression and the right branch is IntegerLiteralExpression.


In the Main method, we take in the user input, create a lexer, pass to Parser ‘s constructor, call parse method to get the AST expression, use Eval static method to get result, and print the result’s Inspect output.

A software developer in Microsoft at Suzhou. Most articles spoken language is Chinese. I will try with English when I’m ready