【发布时间】:2016-03-21 12:45:12
【问题描述】:
考虑以下定义类型对的类型类:
class Constraint a b where
g :: a -> b
对于所有约束实例,我们可以派生一组类型a,本质上是一个隐式类型类,我们称之为A。对于类型类A 的每个实例,都有另一个隐式类型类B,它包括b 的所有可能类型Constraint A b。
所以这里有一段代码。
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Debug.Trace
-- Contraining class
class (Show a, Show b) => QandA a b where
g :: a -> b
-- Some data types
data A = A1 | A2 deriving (Show, Eq)
data B = B1 | B2 deriving (Show, Eq)
data C = C1 | C2 deriving (Show, Eq)
instance QandA A B where
g A1 = B1
g A2 = B2
instance QandA A C where
g A1 = C1
g A2 = C2
-- We want to define a set of types that includes all the types that
-- have Constraint a b given a. This can be done via an intermediate
-- type.
data DefaultAnswer q = forall a . (DefaultingQuestion q, QandA q a) => DefaultAnswer {answer :: a};
-- Polymorphism
class DefaultingQuestion q where
def :: DefaultAnswer q
instance DefaultingQuestion A where
def = DefaultAnswer C1
哪些类型检查但在 ghci 中
> (def :: DefaultAnswer A)
(def :: DefaultAnswer A) :: DefaultAnswer A
但是
> answer (def :: DefaultAnswer A)
<interactive>:574:1:
Cannot use record selector "answer" as a function due to escaped type variables
Probable fix: use pattern-matching syntax instead
In the expression: answer (def :: DefaultAnswer A)
In an equation for "it": it = answer (def :: DefaultAnswer A)
现在我的理解是,由于我使用存在类型,GHC 并没有真正寻找answer 的类型,它只是确保可能存在一个,即使它无法确定是哪一个它是。所以当我真的想运行answer 时,它不知道如何处理它。
所以我的问题是:有没有办法为实现DefaultingQuestion的每种类型定义一个默认答案
【问题讨论】:
-
我认为这行不通,除非您想添加
Typeable约束或其他东西。你能举一些具体的例子来说明你为什么想要这个吗? -
Typeable(或Data)约束是一个可以接受的折衷方案,但我不知道如何处理这些...... -
这段代码太……奇怪了……如果没有更多关于你想要完成什么的背景,我无法给出任何具体的建议。你有用例吗?
标签: haskell typeclass existential-type