1

我定义了这些数据类型:

data Term = Symbol [Char] | Number [Int] 
data Exp = Fun (String, Term) | Exp (String, [Exp])

然后我写了一些显示规则:

instance Show Term where
  show (Symbol [x])     = [x]
  show (Symbol (x:xs))  = [x]++", "++(show (Symbol xs))

  show (Number [x])     = (show x)
  show (Number (x:xs))  = (show x)++", "++(show (Number xs))

instance Show Exp where
  show (Fun (name, args)) = name++"("++(show args)++")"
  show (Exp (name, args)) = name++"("++(show args)++")"

现在,如果我让:

bt = Exp("z", [Fun("f", Number [1,2,3]), Fun("g", Symbol ['a', 'b', 'c'])])

显示它我得到:

z([f(1, 2, 3),g(a, b, c)])

我希望有这种表示:

z(f(1, 2, 3),g(a, b, c))

即里面没有方括号。

有人能帮我吗?

我试图添加这些语句:

instance Show [Exp] where
  show [x]    = show x
  show (x:xs) = (show x)++(show xs)

ghci声称这是注意法律法规。

4

2 回答 2

6

你可以简单地改变这一行:

  show (Exp (name, args)) = name++"("++(show args)++")"

...所以它说:

  show (Exp (name, args)) = name++"("++(intercalate ", " . map show $ args)++")"

该函数intercalate来自Data.List.

于 2012-09-18T12:56:41.670 回答
6

您可以showListShow实例中为Exp.

instance Show Exp where
  show (Fun (name, args)) = name++"("++(show args)++")"
  show (Exp (name, args)) = name++"("++(show args)++")"
  showList [] _ = ""
  showList [x] _ = show x
  showList (x:xs) _ = show x ++ "," ++ show xs
于 2012-09-18T13:47:38.927 回答