实例化新数据类型的Show类

时间:2012-09-18 12:45:31

标签: haskell show

我定义了这些数据类型:

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

然后我写了一些Show规则:

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声称它是合法代码。

2 个答案:

答案 0 :(得分:6)

您只需更改此行:

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

...所以它说:

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

函数intercalate来自Data.List

答案 1 :(得分:6)

您可以在showList实例中为Show定义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