Haskell:显示和漂亮的实例 [英] Haskell: show and pretty-print instance

查看:118
本文介绍了Haskell:显示和漂亮的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在大学开展智能系统研究,我们的第一语言是Haskell。我必须承认,到目前为止我还不是很熟悉它。本周部分任务是开发一个代数数据类型 Expr a ,它代表基本的算术运算(+, - ,*,/)
解决方案IMO应该是:

pre $ 模块表达式,其中

数据Expr a = Number a |
Var |
总和(Expr a)(Expr a)|
Prod(Expr a)(Expr a)|
Div(Expr a)(Expr a)|
Pot(Expr a)a
派生(显示)

到目前为止。目前的任务是为我们的函数实现一个漂亮的实例。即:


$ b

Plus(Pot(Var 2))(Num 3 )





x ^ 2 + 3



所以,我不知道漂亮是什么意思。在搜索互联网后,我发现漂亮只意味着以人类可读形式重写输出。它是否正确?如果是这样,这对我的功能意味着什么?我是否必须用漂亮函数替换 show 函数?我不知道从哪里开始。

我在这里阅读了几个类似的问题,但没有在那里说明问题。我真的很高兴,如果有人能给我一些提示,建议,解决方案或其他任何东西!

解决方案



基本上,您只需要一个将 Expr a 转换为字符串

  myPrettyPrint :: Expr a  - >字符串

无论你想要什么,都可以调用它,并且不要试图替换 show



为了实现此功能,您可能需要了解模式匹配


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!

解决方案

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.

这篇关于Haskell:显示和漂亮的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆