-1

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

toString (Plus e1 e)= ??

我猜它会像

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

1 回答 1

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)))
于 2009-04-03T13:34:46.640 回答