使用PolyKinds的不明确的变量

时间:2017-11-09 11:41:40

标签: haskell ghc polykinds

给出以下代码

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}

type family Tagged (m :: * -> *) :: k

class Example (t :: k) (a :: *) where
  type Return t a
  a :: (Monad m, Tagged m ~ t) => a -> m (Return t a)

data A
data A' a
data B = B

instance Example A B where
  type Return A B = ()
  a B = return ()

-- This is why I want a PolyKinded 't'
instance Example A' B where
  type Return A' B = ()
  a B = return ()

我收到类型错误(指向行a :: (Monad m ...

• Could not deduce: Return (Tagged m) a ~ Return t a
  from the context: (Example t a, Monad m, Tagged m ~ t)
    bound by the type signature for:
               a :: (Example t a, Monad m, Tagged m ~ t) =>
                    a -> m (Return t a)
...
  Expected type: a -> m (Return t a)
    Actual type: a -> m (Return (Tagged m) a)
  NB: ‘Return’ is a type function, and may not be injective
  The type variable ‘k0’ is ambiguous
• In the ambiguity check for ‘a’
  To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
  When checking the class method:
    a :: forall k (t :: k) a.
         Example t a =>
         forall (m :: * -> *).
         (Monad m, Tagged m ~ t) =>
         a -> m (Return t a)
  In the class declaration for ‘Example’

我可以使用aProxy t引入一个参数,如果我在呼叫站点给出签名,这将有效:test = a (Proxy :: Proxy A) B但这是我要避免的。我想要的是

newtype Test t m a = Test
  { runTest :: m a
  } deriving (Functor, Applicative, Monad)

type instance Tagged (Test t m) = t

test :: Monad m => Test A m ()
test = a B

我希望使用类型实例从上下文t中找到Test A m ()。似乎应该可以在删除类型注释PolyKindsA'的实例后编译模块。 k0来自哪里?

我认为解决方法是删除PolyKinds并使用额外的数据类型,如data ATag; data A'Tag; data BTag等。

1 个答案:

答案 0 :(得分:2)

这只是部分答案。

我试图明确表达那种。

type family Tagged k (m :: * -> *) :: k

class Example k (t :: k) (a :: *) where
  type Return k (t :: k) (a :: *)
  a :: forall m . (Monad m, Tagged k m ~ t) => a -> m (Return k t a)

并且,在启用了许多扩展后,观察到了这一点:

> :t a
a :: (Example k (Tagged k m) a, Monad m) =>
     a -> m (Return k (Tagged k m) a)

因此,编译器抱怨,因为仅Example k (Tagged k m) a无法确定实例a,m。也就是说,我们不知道如何选择k

我想,从技术上讲,我们可能会有不同的Example k (Tagged k m) a个实例,例如一个用于k=*,另一个用于k=(*->*)

直观地说,了解t应该可以让我们找到k,但Return是非单射的,阻止我们找到t