Reputation: 33
I started Intelligent System studies at a university and our first language is Haskell. I must admit that I am not really familiar with it so far. Part of this week's task is to develop an algebraic datatype Expr a
which represents the basic arithmetic operations (+,-,*,/)
.
The solution IMO should be:
module Expression where
data Expr a
= Number a
| Var
| Sum (Expr a) (Expr a)
| Prod (Expr a) (Expr a)
| Div (Expr a) (Expr a)
| Pot (Expr a) a
deriving (Show)
Okay so far. The task is to implement a pretty-instance for our function now. i.e.:
from
Plus (Pot (Var 2)) (Num 3)
to
x^2 + 3
So, I had no idea what "pretty" means. After searching the internet I found out that "pretty" only means to rewrite the output in a human readable form. Is this correct? If it is, what does it mean to my function? Do I have to replace the show
function with a pretty
function? I don't really know where to start.
I read several similar questions here but didn't get the point there. I would really be happy if someone could give me some hints, advice, solutions or whatever!
Upvotes: 2
Views: 2668
Reputation: 120711
I'd just implement show
accordingly (instead of deriving from it), which can be done quite easily at least if you don't mind it to include unnecessary parentheses:
instance (show a) => show (Expr a) where
show (Number x) = show x
-- ...
show (Prod x y) = "("++show x++")*("++show y++")"
-- ...
This can be done better and more efficient, but perhaps this solution is sufficient for you.
It was said in comments above that show
should be a lightwight means of serialization and should in particular fulfill (read . show) x = x
. I agree, and it means that you should, for instance, not do any actual prettyprint stuff (like outputting to LaTeX, which would certainly be a nice way of outputting such data). It does, IMO, not mean that show
should always behave like the derived instance, not if this output is unratifiably less readable, longer, and/or less clear if watched without the haskell code as context.
Another point hammar made in the comments above: the output of show
should be valid haskell code. To make my solution conform to that you need to make Expr
an instance of Num
and either Fractional
or Integral
.
Upvotes: 1
Reputation: 49095
Yes, that's what pretty print means.
Basically, you just need a function that converts an Expr a
into a String
:
myPrettyPrint :: Expr a -> String
Call it whatever you want, and don't try to replace show
.
In order to implement this function, you'll probably want to learn about pattern matching.
Upvotes: 7