Haskell: show and pretty-print instance

你。 提交于 2019-12-11 02:44:18

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8217511/haskell-show-and-pretty-print-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!