下面的代码片段从Haskell wiki 借用了一个类型类字典和一个存在类型:
{-# language ExistentialQuantification #-}
module Experiment1 where
data Showable = forall x. Show x => Showable x
instance Show Showable where showsPrec p (Showable x) = showsPrec p x
resultStr :: String
resultStr = show (Showable ()) -- "()"
是否可以编写一个f :: (forall x. x -> result) -> result
能够将Showable
构造函数(或任何其他存在类型的数据构造函数)作为参数的函数?
一次失败的尝试如下所示:
{-# language ExistentialQuantification, RankNTypes, ConstraintKinds #-}
module Experiment2 where
-- import Data.Constraint (Dict(..), withDict)
data Showable = forall x. Show x => Showable x
instance Show Showable where showsPrec p (Showable x) = showsPrec p x
f :: (cxt (), cxt result) => (forall x. cxt x => x -> result) -> result
f mkResult = mkResult ()
resultStr :: String
resultStr = show (f Showable)
正如我上面评论的导入所暗示的那样,我的印象是约束包可能允许我传递必要的证明,但我看不出它是如何工作的?