convert an expression to a string representation?

坚强是说给别人听的谎言 提交于 2019-12-13 14:08:03

问题


Consider the following Haskell code:

module Expr where

    -- Variables are named by strings, assumed to be identifiers:

    type Variable = String

    -- Representation of expressions:

    data Expr = Const Integer
          | Var Variable
          | Plus Expr Expr
          | Minus Expr Expr
          | Mult Expr Expr
          deriving (Eq, Show)


    simplify :: Expr->Expr

    simplify (Mult (Const 0)(Var"x"))
     = Const 0 
    simplify (Mult (Var "x") (Const 0))
     = Const 0
    simplify (Plus (Const 0) (Var "x")) 
    = Var "x"
    simplify (Plus (Var "x") (Const 0))
     = Var "x" 
    simplify (Mult (Const 1) (Var"x")) 
    = Var "x"
    simplify (Mult(Var"x") (Const 1))
     = Var "x" 
    simplify (Minus (Var"x") (Const 0))
     = Var "x"
    simplify (Plus (Const x) (Const y)) 
    = Const (x + y)
    simplify (Minus (Const x) (Const y))
    = Const (x - y)
    simplify (Mult (Const x) (Const y))
     = Const (x * y)
    simplify x = x

    toString :: Expr->String

How can I convert an expression to a string representation?

e.g.

toString (Var "x") = "x"  
toString (Plus (Var "x") (Const 1)) = "x + 1"  
toString (Mult (Plus (Var "x") (Const 1)) (Var "y"))  
       = "(x + 1) * y" 

回答1:


Rather than call your function toString, it might be preferable to use the Show type class. Then your data type can be used anywhere that an instance of Show can be used. Show is the standard Haskell way of converting "things" into strings.

instance Show Expr where
    show (Var "x") = "x"
    -- etc.



回答2:


It looks like you almost have it.

Here's an example

toString (Plus e1 e2) = (toString e1) ++ " + " ++ (toString e2)
toString (Const i) = show i



回答3:


Here is everything you need to know for this: http://augustss.blogspot.com/2007/04/overloading-haskell-numbers-part-1.html



来源:https://stackoverflow.com/questions/321822/convert-an-expression-to-a-string-representation

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