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 find yourself wanting to work with a fixed number of operations, like your arithmetic operations in this case, a sum type is a good first thing to start thinking about. Let’s start by building a basic sum type that will capture these operations. Our type represents an arithmetic expression, so we’ll call it Expr :

​  ​ data ​ ​ Expr ​ = ​ Add ​ | ​ Sub ​ | ​ Mul ​ | ​ Div ​

Next, let’s think about what fields we might want to associate with each of the constructors. These constructors all represent a binary operation. For now we’ll only worry about Int types, so we can add the operands as fields to each constructor:

​  ​ data ​ ​ Expr ​ = ​ Add ​ ​ Int ​ ​ Int ​
​  | ​ Sub ​ ​ Int ​ ​ Int ​
​  | ​ Mul ​ ​ Int ​ ​ Int ​
​  | ​ Div ​ ​ Int ​ ​ Int ​

This is a step forward. We have a data type that we could put data in and get data out of, but it’s pretty limiting because we can’t nest expressions. In our examples we were able to express several different operations in a single expression. To do that we’ll want to make our data type recursive, meaning the operands for each constructor are themselves sub-expressions. That means that we need a base case. Luckily, there’s one sitting in front of us that we overlooked when we originally enumerated our operations. Not only do we have our four binary operations, we also have literal numbers as part of the grammar of our arithmetic expression. Let’s add a new Lit constructor to represent a literal integer, and update the rest of our type to recursively reference sub-expressions:

​  ​ data ​ ​ Expr ​ = ​ Lit ​ ​ Int ​
​  | ​ Sub ​ ​ Expr ​ ​ Expr ​
​  | ​ Add ​ ​ Expr ​ ​ Expr ​
​  | ​ Mul ​ ​ Expr ​ ​ Expr ​
​  | ​ Div ​ ​ Expr ​ ​ Expr ​

Just like you did with peano numbers, you can write a recursive function that will take one of these recursive values and compute a number. Instead of incrementing the number, you’ll decide on an operation based on the constructor for the value:

​  eval :: ​ Expr ​ -> ​ Int ​
​  eval expr =
​  ​ case ​ expr ​ of ​
​  ​ Lit ​ num -> num
​  ​ Add ​ arg1 arg2 -> (eval arg1) + (eval arg2)
​  ​ Sub ​ arg1 arg2 -> (eval arg1) - (eval arg2)
​  ​ Mul ​ arg1 arg2 -> (eval arg1) * (eval arg2)
​  ​ Div ​ arg1 arg2 -> (eval arg1) `div` (eval arg2)

You might notice some duplication here. Except in the case of literal numbers, all our case matches follow the same pattern where we recursively parse each of the two arguments and combine the results with some operation. We can refactor this to reduce the duplication by moving the recursion into a second function, which we’ll call eval’ . The eval’ function will take the two arguments, along with our operator, and handle recursively parsing the two arguments:

​  eval :: ​ Expr ​ -> ​ Int ​
​  eval expr =
​  ​ case ​ expr ​ of ​
​  ​ Lit ​ num -> num
​  ​ Add ​ arg1 arg2 -> eval' (+) arg1 arg2
​  ​ Sub ​ arg1 arg2 -> eval' (-) arg1 arg2
​  ​ Mul ​ arg1 arg2 -> eval' (*) arg1 arg2
​  ​ Div ​ arg1 arg2 -> eval' div arg1 arg2
​  ​ where ​
​  eval' :: (​ Int ​ -> ​ Int ​ -> ​ Int ​) -> ​ Expr ​ -> ​ Expr ​ -> ​ Int ​
​  eval' operator arg1 arg2 =
​  operator (eval arg1) (eval arg2)

With your new eval function in hand, you can start writing some expressions and evaluating them to numbers. Try loading your program up in ghci and evaluating a few expressions:

​  ​ λ ​ eval $ ​ Add ​ (​ Lit ​ 1) (​ Lit ​ 2)
​  3
​  ​ λ ​ eval $ ​ Sub ​ (​ Lit ​ 10) (​ Div ​ (​ Lit ​ 10) (​ Lit ​ 2))
​  5
​  ​ λ ​ eval $ ​ Add ​ (​ Lit ​ 5) (​ Sub ​ (​ Lit ​ 10) (​ Div ​ (​ Lit ​ 10) (​ Lit ​ 2)))
​  10

Remember that value constructors are normal functions, so you can use backticks to make them work as infix functions. If you find infix notation easier to read, give it a try:

​  ​ λ ​ eval $ ​ Lit ​ 5 `​ Add ​` (​ Lit ​ 10 `​ Sub ​` (​ Lit ​ 10 `​ Div ​` ​ Lit ​ 2))
​  10

You’ll quickly notice that entering expressions by manually writing out all of the constructors is pretty obnoxious. Let’s create a parser that will allow us to write nice expressions, like we did in the example we used to start this section. We’ll call our parse function parse and it’ll take a string as input. In the best-case scenario, we’d like to return an Expr value, but we’ll need to account for erroneous input, since not every string is a valid arithmetic expression. Let’s give our function the type: parse :: String -> Either String Expr .

We’ll build our parser out in a few separate pieces, focusing on one step at a time. The first part of our parser will tokenize our input string, hand off the majority of the parsing to a second function, parse’ , and then do some final error handling before returning a value. In particular, we’ll look for errors where parse’ gives us back a Left value, because it found an error, or the case where it gives us a Right value, but tells us that it didn’t parse all of the tokens. Let’s start by writing parse and then we’ll move on to filling in some additional details by writing parse’ :

​  parse :: ​ String ​ -> ​ Either ​ ​ String ​ ​ Expr ​
​  parse str =
​  ​ case ​ parse' (words str) ​ of ​
​  ​ Left ​ err -> ​ Left ​ err
​  ​ Right ​ (e,​ [] ​) -> ​ Right ​ e
​  ​ Right ​ (​ _ ​,rest) -> ​ Left ​ $ ​ "Found extra tokens: " ​ <> (unwords rest)

The two functions that we’re using from Prelude, words and unwords , work with strings. The words function takes an input string and splits it up along blank space boundaries, returning a list of strings. The unwords function, intuitively, does the opposite, taking a list of strings and joining them all with spaces.

With the top level function written, it’s time to move on to the next part of the parser. Because these functions are helpers that are highly coupled to the implementation of parse , add them as let or where bindings rather than top level functions.

The parse’ function is where we’ll handle individual tokens. The shape of this function is quite similar to eval function that you have already written. We’ll start with a case statement to look at the specific token that we’re parsing.

To parse a literal value, we can use a function from the standard library named readEither from the Text.Read module. This function will try to parse a String value into some other value, in our case an Int . As you can imagine, not all strings can be converted into numbers. To handle errors, readEither will either return Right with our converted value, or Left with an error message.

Even though readEither is part of the standard library, it’s not in scope by default. We’ll need to import a new module to use it. You’ll learn more about modules, and how to import things, in the next chapter. For now you can copy the import statement from the example directly into your code:

​  ​ module ​ ​ Calculator ​ ​ where ​
​  
​  ​ import ​ ​ Text.Read ​ (​ readEither ​)

For the operators in our expression, we’ll need to recursively parse the arguments to the expression by looking at the rest of the string. Just like in eval , we’ll factor the recursive function out into a helper. We’ll call our helper function parseBinary , since it’s parsing a binary operator , which is an operator that takes two arguments:

​  parse' :: [​ String ​] -> ​ Either ​ ​ String ​ (​ Expr ​,[​ String ​])
​  parse' ​ [] ​ = ​ Left ​ ​ "unexpected end of expression" ​
​  parse' (token:rest) =
​  ​ case ​ token ​ of ​
​  ​ "+" ​ -> parseBinary ​ Add ​ rest
​  ​ "*" ​ -> parseBinary ​ Mul ​ rest
​  ​ "-" ​ -> parseBinary ​ Sub ​ rest
​  ​ "/" ​ -> parseBinary ​ Div ​ rest
​  lit ->
​  ​ case ​ readEither lit ​ of ​
​  ​ Left ​ err -> ​ Left ​ err
​  ​ Right ​ lit' -> ​ Right ​ (​ Lit ​ lit', rest)

You might wonder why we’re returning a tuple of an expression and a list of strings here. This is a common pattern when implementing recursive parsers. The idea is that each recursive call will consume some part of the input, and will return the remainder of the input, allowing the caller to make forward progress through the list of tokens. This will make a bit more sense after you implement the parseBinary function, so let’s move on to that next:

​  parseBinary ::
​  (​ Expr ​ -> ​ Expr ​ -> ​ Expr ​)
​  -> [​ String ​]
​  -> ​ Either ​ ​ String ​ (​ Expr ​, [​ String ​])
​  parseBinary exprConstructor args =
​  ​ case ​ parse' args ​ of ​
​  ​ Left ​ err -> ​ Left ​ err
​  ​ Right ​ (firstArg,rest') ->
​  ​ case ​ parse' rest' ​ of ​
​  ​ Left ​ err -> ​ Left ​ err
​  ​ Right ​ (secondArg,rest'') ->
​  ​ Right ​ $ (exprConstructor firstArg secondArg, rest'')

You can see that parseBinary looks similar to the eval’ function that you wrote earlier. Instead of some arithmetic operator, it receives one of your Expr constructors. Instead of evaluating arguments recursively, it parses them. We’ve also had to add some error handling to account for the fact that parsing might fail.

Looking through the implementation of this function, we can now start to understand the reason for returning a tuple rather than an expression. As we parse the arguments for our operators, we have to know where to start parsing the second argument. To handle that, when we start parsing the first argument, we have it give us back the remainder of the string that it hasn’t parsed, and we can use that remainder to start parsing the second argument.

Finally, as a matter of convenience, let’s write one more function to make it easier to call our parser and evaluate the result. We’ll call this function run and it will have the type run :: String -> String :

​  run :: ​ String ​ -> ​ String ​
​  run expr =
​  ​ case ​ parse expr ​ of ​
​  ​ Left ​ err -> ​ "Error: " ​ <> err
​  ​ Right ​ expr' ->
​  ​ let ​ answer = show $ eval expr'
​  ​ in ​ ​ "The answer is: " ​ <> answer