Ara*_*ian 8 haskell existential-type
我试图将我的大脑包裹在Haskell的存在类型中,我的第一个例子是可以显示的异构事物列表:
{-# LANGUAGE ExistentialQuantification #-}
data Showable = forall a. Show a => Showable a
showableList :: [Showable]
showableList = [Showable "frodo", Showable 1]
Run Code Online (Sandbox Code Playgroud)
现在在我看来,我想做的下一件事就是让Showable成为Show的一个实例,这样,例如,我的showableList可以显示在repl中:
instance Show Showable where
show a = ...
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我真正想要做的就是调用a的底层show实现.但是我在提到它时遇到了麻烦:
instance Show Showable where
show a = show a
Run Code Online (Sandbox Code Playgroud)
选择Showable在RHS上的show方法,这个方法在圈子里运行.我尝试了自动派生Show,但这不起作用:
data Showable = forall a. Show a => Showable a
deriving Show
Run Code Online (Sandbox Code Playgroud)
给我:
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'
Run Code Online (Sandbox Code Playgroud)
我正在寻找一些调用底层的Show :: show实现,以便Showable不必重新发明轮子.
Log*_*ldo 17
instance Show Showable where
show (Showable a) = show a
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1495 次 |
最近记录: |