我正试图将我的大脑包裹在Haskell的存在类型中,我的第一个例子是可以显示的异类列表:
{-# LANGUAGE ExistentialQuantification #-}
data Showable = forall a. Show a => Showable a
showableList :: [Showable]
showableList = [Showable "frodo", Showable 1]
现在在我看来,我想做的下一件事就是让Showable成为Show的一个实例,这样,例如,我的showableList可以显示在repl中:
instance Show Showable where
show a = ...
我遇到的问题是我真正想要做的是调用 a 的底层 show 实现。但我无法提及它:
instance Show Showable where
show a = show a
在RHS中选择 Showable 的show方法,该方法在圈子中运行。我尝试了自动派生Show,但这不起作用:
data Showable = forall a. Show a => Showable a
deriving Show
给了我:
Can't make a derived instance of `Show Showable':
Constructor `Showable' does not have a Haskell-98 type
Possible fix: use a standalone deriving declaration instead
In the data type declaration for `Showable'
我正在寻找调用底层的Show :: show实现,以便 Showable 不必重新发明轮子。
答案 0 :(得分:17)
instance Show Showable where
show (Showable a) = show a
show a = show a
无法正常工作,因为它无限地递归。如果我们在没有存在类型的情况下尝试这个,我们可以看到相同的问题和解决方案
data D = D Int
instance Show D where show a = show a -- obviously not going to work
instance Show D where show (D a) = "D " ++ (show a) -- we have to pull out the underlying value to work with it