如何正确绑定此类型变量?

How do you bind this type variable correctly?

我一直在挖掘一些旧代码(坦率地说,对一些设计决定感到遗憾),但我意识到我永远无法编译最终函数,而且我真的不明白为什么。我有 ScopedTypeVariables,通常可以为我解决这样的问题。

{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, FlexibleContexts, RankNTypes #-}
{-# LANGUAGE DeriveTraversable, DerivingStrategies, ScopedTypeVariables #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE AllowAmbiguousTypes #-}

import Prelude hiding ((+), (*))
import Algebra
import Control.Lens.TH (makeLenses)
import Data.Semigroup (Semigroup, (<>))
import Data.Monoid (mempty, mappend)
import Data.Proxy (Proxy)
import Data.Function(on)
import qualified Data.IntMap as IM
import Control.Lens (IxValue, Index, Ixed(..), Traversal', Iso', view, review)

class (Ixed g) => Grid g where
    -- Stored x first, then y
    gridIso :: Iso' g (IM.IntMap (IM.IntMap (IxValue g)))
    storageVector :: (Index g) -> Vector2D Int

{-# INLINE gridIx #-}
gridIx :: forall g . (Grid g) => (Index g) -> Traversal' g (IxValue g)
gridIx v = gridIso . (ix x) . (ix y) 
   where (Vector2D x y) = storageVector v

相反,我得到了这个:

/mnt/c/Users/me/advent2018/src/Vector.hs:92:41: error:
    • Couldn't match expected type ‘Index g0’
                  with actual type ‘Index g’
      NB: ‘Index’ is a non-injective type family
      The type variable ‘g0’ is ambiguous
    • In the first argument of ‘storageVector’, namely ‘v’
      In the expression: storageVector v
      In a pattern binding: (Vector2D x y) = storageVector v
    • Relevant bindings include
        v :: Index g
          (bound at /mnt/c/Users/me/advent2018/src/Vector.hs:91:8)
        gridIx :: Index g -> Traversal' g (IxValue g)
          (bound at /mnt/c/Users/me/advent2018/src/Vector.hs:91:1)

这里发生的事情是,为了调用 storageVector,编译器必须选择 Grid 的实例,但它不能。

通常情况下,参数类型足以选择实例,但在这种情况下,参数的类型为 Index g,并且 Index 是非单射类型族(如错误消息状态),这意味着您可以从 g 转到 Index g,但不能返回。也就是说,仅仅知道Index g是没办法知道g是什么的。

因此编译器无法选择 Grid 实例并拒绝该程序。

为了帮助编译器解决这个问题,您可以显式指定应该用于实例查找的类型。为此,请使用 TypeApplications 扩展名:

    where (Vector2D x y) = storageVector @g v

这将告诉编译器它应该为相同的 g 使用实例 Grid g

请注意,要使其正常工作,使用 forall 关键字声明 g 至关重要,您已经在这样做了。