ghci> show (Left 3)
"Left 3"
ghci> show (Just 0)
"Just 0"
ghci> show (Just (Left 3))
"Just (Left 3)"
Haskell如何自动将圆括号放在嵌套的构造函数参数周围?
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
showsPrec
, showString
, showParen
等作用于差异列表(ShowS = String -> String
),其中参数是一个附加到结果的字符串。连接通过组合完成,并通过应用程序将其转换为带有空字符串的String
。show
的实现使用优先级最低的showsPrec
、要打印的表达式,最后是字符串的结尾[]
。