Jam*_*pel 5 polymorphism haskell typeclass
这是一个非常有用的课程:
class Foo f a where
foo :: f a
Run Code Online (Sandbox Code Playgroud)
它让我为很多类型制作默认值.事实上,我甚至可能不需要知道它是什么a.
instance Foo Maybe a where
foo = Nothing
Run Code Online (Sandbox Code Playgroud)
现在我有一个Maybe a为所有人a,我可以在以后专门.
specialize :: (forall a. f a) -> f Int
specialize x = x
fooMaybe :: Maybe Int
fooMaybe = specialize foo
Run Code Online (Sandbox Code Playgroud)
嗯......这fooMaybe看起来确实非常具体.让我们看看我是否可以使用上下文来概括它:
fooAll :: (Foo f a) => f Int
fooAll = specialize foo
Run Code Online (Sandbox Code Playgroud)
哎呀!可能不会.
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
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,我怎么写fooAll,广义版fooMaybe?或者,更一般地说,我如何普遍推广类型类约束?
目前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)
Run Code Online (Sandbox Code Playgroud)