2008-11-26 89 views
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" 

回答

1

看起來你幾乎有它。

下面是一個例子

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

而不是調用函數的toString,這可能是最好使用Show type class。那麼你的數據類型可以用在任何可以使用Show實例的地方。 Show是標準的Haskell將「事物」轉換爲字符串的方式。

instance Show Expr where 
    show (Var "x") = "x" 
    -- etc. 
相關問題