为仿函数组合定义Show

Sal*_*Sal 1 haskell composition functor typeclass

如果已经提出这个问题我很抱歉.Show是一个非常常见的关键字,使我很难切断噪音.如果我有一个functor composition如下所示定义的类型,我无法弄清楚如何Show为该类型定义实例:

newtype FComp f g a = C { unC :: f (g a) }

--- Incomplete Show definition for FComp
instance Show (FComp f g a) where
  show (C x) = "FComp" ++ show ??? --- Given a type say FComp Maybe Maybe Int, should print out "FComp Maybe Maybe Int"
Run Code Online (Sandbox Code Playgroud)

也:

$ :t show
show :: Show a => a -> String
Run Code Online (Sandbox Code Playgroud)

所以,似乎show接受一个值,并返回相应的字符串.堵xshow ???将无法工作,因为Show实例仍然需要对类型进行定义f (g a).

Dan*_*zer 7

是的,您只需将其添加为您的实例的约束

instance (Show (f (g a))) => Show (FComp f g a) where
  show (C f) = "FComp " ++ show f
Run Code Online (Sandbox Code Playgroud)

这只是意味着我们有一个show instance FComp实际上我们有一个forf (g a)

您还需要启用-XFlexibleContexts此功能,但我不担心这一点,它只是放宽对GHC允许上下文的限制,并且是非常有争议的.

  • 不应该是`show(C f)="FComp"++ show f`和`ghci`告诉我需要启用`FlexibleContexts` (2认同)