我有一个聪明的类型级机械,适用于GHC 7.6但不是更高版本。回顾过去,我并不完全确定它为什么会起作用,但无论如何我想以某种方式取回这个功能:
{-# LANGUAGE
PolyKinds
, FunctionalDependencies , FlexibleInstances , FlexibleContexts
, OverlappingInstances
, ScopedTypeVariables
, TypeFamilies
, UndecidableInstances
#-}
module M where
import Data.Proxy
-- | A relation between a (maybe-partially-applied) type and that type fully
-- applied.
class Applied t (tab :: *) | t -> tab where
-- | Fully apply a type @t@ with polymorphic arguments, yielding @tab@.
applied :: Proxy t -> Proxy tab
instance Applied (t a) tab=> Applied t tab where
applied _ = applied (Proxy :: Proxy (t a))
instance t ~ tab=> Applied t tab where -- always matches when `t` is kind `*`
applied _ = Proxy :: Proxy tab
这取决于GHC 7.6上的tagged
库。我们可以像:
$ ghci-7.6.3
Prelude> :l M.hs
[1 of 1] Compiling M ( M.hs, interpreted )
Ok, modules loaded: M.
*M>
*M> :t applied (Proxy :: Proxy Either)
applied (Proxy :: Proxy Either) :: Proxy (Either a a1)
*M> (return $ Right 'a') == applied (Proxy :: Proxy Either)
True
然而,这至少不能在GHC 7.8.3或更高版本上编译:
$ ghci-7.8.3
GHCi, version 7.8.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :l M.hs
[1 of 1] Compiling M ( M.hs, interpreted )
M.hs:19:10:
Could not deduce (Applied (t a0) tab)
arising from the ambiguity check for an instance declaration
from the context (Applied (t a) tab)
bound by an instance declaration:
Applied (t a) tab => Applied t tab
at M.hs:19:10-42
The type variable ‘a0’ is ambiguous
In the ambiguity check for:
forall (k :: BOX) (k1 :: BOX) (t :: k1 -> k) tab (a :: k1).
Applied (t a) tab =>
Applied t tab
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
In the instance declaration for ‘Applied t tab’
M.hs:19:10:
Illegal instance declaration for ‘Applied t tab’
The liberal coverage condition fails in class ‘Applied’
for functional dependency: ‘t -> tab’
Reason: lhs type ‘t’ does not determine rhs type ‘tab’
In the instance declaration for ‘Applied t tab’
Failed, modules load
我认为answer here是相关的,但我还没有理解这个建议。
我可以解决这个问题。我使用这个类的唯一地方是签名形式:
instance (Foo tab, Applied t tab)=> Bar (Proxy t) where
这可能表明我希望Foo
类型多态,但这是一个大型复杂的库,我不知道这种改变是否可行。
答案 0 :(得分:1)
如果我摆脱FD,你的ghci示例在ghc-7.8.3中适用于我,并启用-XAllowAmbiguousTypes
。该扩展程序将要求您在ScopedTypeVariables
中使用该applied
函数时使用instance (Foo tab, Applied t tab)=> Bar (Proxy t)
函数的类型进行注释。