We’ve told you how powerful and expressive Haskell’s type system is. We’ve shown you a lot of ways to use that power. Here’s a chance to really see that in action.

Back in Numeric Types, we showed the numeric typeclasses that come with Haskell. Let’s see what we can do by defining new types and utilizing the numeric typeclasses to integrate them with basic mathematics in Haskell.

To begin let’s think through what we’d
like to see out of *ghci* when we
interact with our new types. To start with, it might be nice to render
numeric expressions as strings, making sure to indicate proper
precedence. Perhaps we could create a function called `prettyShow`

to do that. We’ll show you how to
write it in a bit, but first we’ll look at how we might use it:

`ghci>`

[1 of 1] Compiling Main ( num.hs, interpreted ) Ok, modules loaded: Main.`:l num.hs`

`ghci>`

8`5 + 1 * 3`

`ghci>`

"5+(1*3)"`prettyShow $ 5 + 1 * 3`

`ghci>`

"(5*1)+3"`prettyShow $ 5 * 1 + 3`

That looks nice, but it wasn’t all that
smart. We could easily simplify out the ```
1
*
```

part of the expression. How about a function to do some very
basic simplification?

`ghci>`

"5+3"`prettyShow $ simplify $ 5 + 1 * 3`

How about converting a numeric
expression to *Reverse Polish Notation* (RPN)? RPN is a postfix notation that never requires parentheses and is commonly found on HP calculators. RPN is a stack-based notation. We push numbers onto the stack, and when we enter operations, they pop the most recent numbers off the stack and place the ...

Start Free Trial

No credit card required