如何用Rank-2类型抽象函数中的约束?

时间:2018-01-03 01:58:20

标签: haskell typeclass existential-type constraint-kinds

下面的代码片段从the 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)

正如我上面评论的导入所暗示的那样,我认为constraints包可能允许我传递必要的证据,但我无法看到它会如何起作用?

2 个答案:

答案 0 :(得分:1)

如果您提供了确定cxt

的方法,那么失败的尝试就有效
import Data.Proxy

f :: (cxt (), cxt result) => p cxt -> (forall x. cxt x => x -> result) -> result
f _ mkResult = mkResult ()

resultStr :: String
resultStr = show (f (Proxy :: Proxy Show) Showable)

答案 1 :(得分:0)

我为发布自己的答案而道歉,但这是我最终找到的另一种选择:

{-# language ExistentialQuantification, RankNTypes, ConstraintKinds, KindSignatures, TypeFamilies, FlexibleInstances #-}

module Experiment3 where

import GHC.Exts

data Showable (cxt :: * -> Constraint) = forall x. (cxt ~ Show, cxt x) => Showable x
instance Show (Showable Show) where showsPrec p (Showable x) = showsPrec p x

f :: cxt () => (forall x. cxt x => x -> result cxt) -> result cxt
f mkResult = mkResult ()

resultStr :: String
resultStr = show (f Showable :: Showable Show)

不幸的是,它需要show (f Showable)中的显式类型签名,而我的目标是通过Showable获取类型推断(或者更确切地说,某种约束推断)。所以这个答案不是这样的解决方案,而是我想要的另一个反例。

我会接受Cirdec的回答,因为它引导我得出这个结论。