实现Show类

Mat*_*hid 7 haskell

假设我们有以下内容:

data Foo x
from_list :: [x] -> Foo x
to_list :: Foo x -> [x]

假设我想声明instance (Show x) => Show (Foo x)显示一个值产生适当的调用from_list.我到底该怎么做?特别是,我如何实现showsPrec以满足trixy fiddly优先规则?(也就是说,当且仅在必要时将表达式放在括号中.)

ham*_*mar 18

你想要的这里基本上是一样的东西Data.Set,所以我们可以只修改了一点:

instance Show x => Show (Foo x) where
  showsPrec p xs = showParen (p > 10) $
    showString "from_list " . shows (to_list xs)
Run Code Online (Sandbox Code Playgroud)

换句话说,如果周围上下文的优先级高于函数应用程序(优先级为10),我们将Show实例用于列表,前面加上"from_list "它,并用于showParen在其周围添加括号.

> show (from_list [1, 2, 3])
"from_list [1,2,3]"
> show (Just $ from_list [1, 2, 3])
"Just (from_list [1,2,3])"
Run Code Online (Sandbox Code Playgroud)