Building a Calculator

Now that you have some experience working with sum types and implementing inductively defined data structures, let’s put that knowledge into action and build a more sophisticated application. In this section, you’ll build a small program to parse and evaluate arithmetic expressions in prefix notation. Before you start building the program, let’s look at some examples of the application running:

 λ​ run ​"+ 3 5"
 "The answer is: 8"
 λ​ run ​"/ 16 4"
 "The answer is: 4"
 λ​ run ​"* 2 / 16 4"
 "The answer is: 8"
 λ​ run ​"- 10 + 1 * 2 / 8 4"
 "The answer is: 5"

As you can see in the examples, you’ll need to support four different operations: addition, subtraction, multiplication, and division. Whenever you ...

Get Effective Haskell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.