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:
:l num.hs[1 of 1] Compiling Main ( num.hs, interpreted ) Ok, modules loaded: Main.
5 + 1 * 38
prettyShow $ 5 + 1 * 3"5+(1*3)"
prettyShow $ 5 * 1 + 3"(5*1)+3"
That looks nice, but it wasn’t all that
smart. We could easily simplify out the
* part of the expression. How about a function to do some very
prettyShow $ simplify $ 5 + 1 * 3"5+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 ...