如何在字符串表示中添加两个项目?

时间:2008-11-29 00:28:42

标签: haskell functional-programming lambda-calculus

例如,我想添加两个表达式e1和e2

toString (Plus e1 e)= ??

我猜它会像

toString (Plus e1 e)= ((toString e1) ++ "+" ++ (toString e2))

1 个答案:

答案 0 :(得分:1)

我对如何定义Plus做了一些假设。使用此代码,您只需在ghci提示符下键入expr,ghci将打印出100-30 + 100 + 30的表达式。

module Main where

data Expr =
    Plus Expr Expr
  | Minus Expr Expr
  | Value Int

-- This works but is not as Haskell-y as using Show
toString (Plus e1 e2) = toString e1 ++ "+" ++ toString e2
toString (Minus e1 e2)  = toString e1 ++ "-" ++ toString e2
toString (Value n) = show n

instance Show Expr where
  show (Plus e1 e2) = show e1 ++ "+" ++ show e2
  show (Minus e1 e2)  = show e1 ++ "-" ++ show e2
  show (Value n) = show n

expr = (Plus
         (Minus (Value 100) (Value 30))
         (Plus (Value 100) (Value 30)))