ghci> show (Left 3)
"Left 3"
ghci> show (Just 0)
"Just 0"
ghci> show (Just (Left 3))
"Just (Left 3)"
Haskell如何自動在嵌套構造函數參數周圍放置括號?`Show`實例中的自動括號
ghci> show (Left 3)
"Left 3"
ghci> show (Just 0)
"Just 0"
ghci> show (Just (Left 3))
"Just (Left 3)"
Haskell如何自動在嵌套構造函數參數周圍放置括號?`Show`實例中的自動括號
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
以最低優先級,表達式打印,最後,字符串結尾爲[]
。
每當你深入樹中時,它是否會以某種方式遞增優先參數'p'?在你的情況下,它看起來不像'p'每次都增加。 – CMCDragonkai
在遞歸調用中,「p」被設置爲包含優先級+1。 – Piezoid
真的很短的答案是['showsPrec'](http://hackage.haskell.org/package/base-4.7.0.0/docs/Prelude.html#t:Show),但這本身並不是很有用.. – Carl
['GHC.Show'](http://hackage.haskell.org/package/base-4.7.0.0/docs/src/GHC-Show.html)提供了'showsPrec'的實際實現, Maybe'。 –