Haskell 广义约束
下面是一个非常有用的类:Haskell 广义约束,haskell,polymorphism,typeclass,Haskell,Polymorphism,Typeclass,下面是一个非常有用的类: class Foo f a where foo :: f a 让我为许多类型设置默认值。事实上,我甚至不需要知道什么是a instance Foo Maybe a where foo = Nothing 现在我有了一个可能是一个用于所有a,以后我可以专门化它 specialize :: (forall a. f a) -> f Int specialize x = x fooMaybe :: Maybe Int fooMaybe = speciali
class Foo f a where
foo :: f a
让我为许多类型设置默认值。事实上,我甚至不需要知道什么是a
instance Foo Maybe a where
foo = Nothing
现在我有了一个可能是一个用于所有a
,以后我可以专门化它
specialize :: (forall a. f a) -> f Int
specialize x = x
fooMaybe :: Maybe Int
fooMaybe = specialize foo
嗯……这似乎很具体。让我们看看是否可以使用上下文来概括它:
fooAll :: (Foo f a) => f Int
fooAll = specialize foo
哎呀!我想不是
Foo.hs:18:21:
Could not deduce (Foo * f a1) arising from a use of `foo'
from the context (Foo * f a)
bound by the type signature for fooAll :: Foo * f a => f Int
at Foo.hs:17:11-28
所以,我的问题是,我如何编写fooAll
,这是fooomaybe
的通用版本?或者,更一般地说,我怎样才能通用化一个类型类约束呢?目前在当前的Haskell中没有好的方法。这个包提供了一种可能的类型,尽管我最近发现了如何打破它。仍然可能是你最好的选择,因为如果有人知道如何正确操作,它可能会得到更新
fooAll :: Forall (Foo f) => f Int
fooAll = specialize foo_f where
foo_f :: forall a. f a
foo_f = foo \\ (inst `trans` (Sub Dict) :: () :- Foo f a)
你不能。好的,如果您创建一个实例Foo f a,其中Foo=undefined
,那么您可以编写fooAll
。但那没用。您不能普遍量化约束,也不能编写fooAll::(对于所有a.Foo f a)=>f Int
。