`Show`实例中的自动括号

The*_*nce 4 haskell

ghci> show (Left 3)
"Left 3"
ghci> show (Just 0)
"Just 0"
ghci> show (Just (Left 3))
"Just (Left 3)"
Run Code Online (Sandbox Code Playgroud)

Haskell如何自动将括号放在嵌套的构造函数参数周围?

Pie*_*oid 8

showsPrec :: Int -> a -> ShowS是内部使用的函数,用于show将括号括在一个术语周围.

Int参数指示外部上下文的优先级.如果当前构造函数的优先级大于上下文的优先级,则showParen :: Bool -> ShowS -> ShowS在构造函数周围放置括号.这是一个非常基本的AST的例子:

data Exp = Exp :+: Exp
         | Exp :*: Exp

-- The precedence of operators in haskell should match with the AST shown
infixl 6 :+: 
infixl 7 :*:


mul_prec, add_prec :: Int
mul_prec = 7
add_prec = 6

instance Show Exp where
  showsPrec p (x :+: y) = showParen (p > add_prec) $ showsPrec (add_prec+1) x
                                                   . showString " :+: "
                                                   . showsPrec (add_prec+1) y
  showsPrec p (x :*: y) = showParen (p > mul_prec) $ showsPrec (mul_prec+1) x
                                                   . showString " :*: "
                                                   . showsPrec (mul_prec+1) y
  show t = showsPrec 0 t "" -- Default definition
Run Code Online (Sandbox Code Playgroud)

showsPrec,showString,showParen等,作用于差分列表(ShowS = String -> String),其中,所述参数是附加到该结果的字符串.连接由组合完成,String并由应用程序转换为空字符串.在show执行使用showsPrec优先级最低,表达式打印,最后,该字符串的结尾 [].