实例化新数据类型的Show类

Asl*_*986 1 haskell show

我定义了这些数据类型:

data Term = Symbol [Char] | Number [Int] 
data Exp = Fun (String, Term) | Exp (String, [Exp])
Run Code Online (Sandbox Code Playgroud)

然后我写了一些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)++")"
Run Code Online (Sandbox Code Playgroud)

现在,如果我让:

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

显示它我得到:

z([f(1, 2, 3),g(a, b, c)])
Run Code Online (Sandbox Code Playgroud)

我更愿意有这样的表述:

z(f(1, 2, 3),g(a, b, c))
Run Code Online (Sandbox Code Playgroud)

即内部没有方括号.

有人能帮我吗?

我试着添加这些语句:

instance Show [Exp] where
  show [x]    = show x
  show (x:xs) = (show x)++(show xs)
Run Code Online (Sandbox Code Playgroud)

ghci声称它注意到了法律代码.

dfl*_*str 6

您只需更改此行:

  show (Exp (name, args)) = name++"("++(show args)++")"
Run Code Online (Sandbox Code Playgroud)

......所以它说:

  show (Exp (name, args)) = name++"("++(intercalate ", " . map show $ args)++")"
Run Code Online (Sandbox Code Playgroud)

功能intercalate来自Data.List.


Sat*_*vik 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
Run Code Online (Sandbox Code Playgroud)