3

考虑以下 Haskell 代码:

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

如何将表达式转换为字符串表示?

例如

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

3 回答 3

3

与其调用你的函数 toString,不如使用Show type class。然后,您的数据类型可以在可以使用 Show 实例的任何地方使用。Show 是将“事物”转换为字符串的标准 Haskell 方法。

instance Show Expr where
    show (Var "x") = "x"
    -- etc.
于 2008-11-26T22:36:44.620 回答
1

看起来你几乎拥有它。

这是一个例子

toString (Plus e1 e2) = (toString e1) ++ " + " ++ (toString e2)
toString (Const i) = show i
于 2008-11-26T20:24:50.830 回答
0

这是您需要知道的一切:http ://augustss.blogspot.com/2007/04/overloading-haskell-numbers-part-1.html

于 2008-11-26T19:21:07.197 回答