show (Just 0) "Just 0" ghci> show (Just (Left 3)) "Just (Left 3)" ...">

Automatic parentheses in `Show` instances

ghci> show (Left 3)
"Left 3"
ghci> show (Just 0)
"Just 0"
ghci> show (Just (Left 3))
"Just (Left 3)"

How does Haskell automatically place parentheses around nested constructor arguments?

+4
source share
1 answer

showsPrec :: Int -> a -> ShowSis a function used internally by showto sequentially put parentheses around a term.

The parameter Intindicates the priority of the external context. If the priority of the current constructor is greater than the priority of the context, showParen :: Bool -> ShowS -> ShowSputs parentheses around the constructor. Here is an example for a very simple 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 , , , [].

+7

Source: https://habr.com/ru/post/1544423/


All Articles