Planting Trees
Consider a binary tree with a type:
| | data BinaryTree a = Leaf | Branch ( BinaryTree a) a ( BinaryTree a) |
Write the definition of the binary tree type, and then add the following functions:
| | -- Turn a binary tree of strings into a pretty-printed string |
| | showStringTree :: BinaryTree String -> String |
| | |
| | -- Add a new integer into a binary tree of integers |
| | addElementToIntTree :: BinaryTree Int -> Int -> BinaryTree Int |
| | |
| | -- Check to see if an int value exists in a binary tree of ints |
| | doesIntExist :: BinaryTree Int -> Int -> Bool |
Eval Division by Zero
Write a new version of your eval function named safeEval that will return an error if the user tries to divide by zero. It should have the type:
| | safeEval :: Expr -> Either String Int |
Here’s an example of the output you should expect when using safeEval :
| | λ> eval $ Lit 10 `Div` Lit 0 |
| | *** Exception: divide by zero |
| | λ> safeEval $ Lit 10 `Div` Lit 0 |
| | Left "Error: division by zero" |
| | λ> safeEval $ Lit 10 `Div` Lit 10 |
| | Right 1 |
Hint: You may need to make quite a few changes to your eval function to complete this exercise, but no changes to your Expr type should be necessary, and you should not need to write any additional functions.
Calculator Pretty Printer
Write a new function, prettyPrint , with the type:
| | prettyPrint :: Expr -> String |
The function should take any expression and return a human readable string that shows the calculation as someone might write it themselves.
| | λ putStrLn $ prettyPrint $ Lit 5 ` Add ` Lit 10 |
| | 5 + 10 = 15 |
| | λ putStrLn $ prettyPrint $ Lit 5 ` Add ` ( Lit 10 ` Div ` Lit 2) |
| | 5 + ( 10 ÷ 2 ) = 10 |
| | λ putStrLn $ prettyPrint $ Lit 14 ` Mul ` ( Lit 5 ` Add ` ( Lit 10 ` Div ` Lit 2)) |
| | 14 × ( 5 + ( 10 ÷ 2 ) ) = 140 |
Footnotes
[2]
https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts.html
Copyright © 2023, The Pragmatic Bookshelf.