haskellpretty-print

Haskell: show and pretty-print instance


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!


Solution

  • 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.