在这个例子中有没有办法避免UndecidableInstances?

时间:2016-01-05 04:45:32

标签: haskell haskell-vector

当我尝试这个时:

import GHC.Generics (Generic)
import Control.DeepSeq (NFData(..))
import Data.Vector.Generic (Vector)

data Entry a = Entry !Bool a
             deriving (Generic, NFData)

-- The variable @v@ is meant to be instantiated with a 'Vector'
-- type.  Most operations for the type have a @Vector v (Entry a)@
-- constraint.
newtype DenseIntMap v a = DenseIntMap (v (Entry a))

instance NFData (v (Entry a)) => NFData (DenseIntMap v a) where
  rnf (DenseIntMap va) = rnf va

...我收到此错误:

/Users/casillas/GitHub/tau-sigma/src/TauSigma/Util/DenseIntMap.hs:53:10:
    Constraint is no smaller than the instance head
      in the constraint: Vector v (Entry a)
    (Use UndecidableInstances to permit this)
    In the instance declaration for ‘NFData (DenseIntMap v a)’

/Users/casillas/GitHub/tau-sigma/src/TauSigma/Util/DenseIntMap.hs:53:10:
    Constraint is no smaller than the instance head
      in the constraint: NFData (v (Entry a))
    (Use UndecidableInstances to permit this)
    In the instance declaration for ‘NFData (DenseIntMap v a)’

使用UndecidableInstances确实让它消失了,但我担心使用该扩展名。在这种情况下,还有其他方法可以使事情发挥作用吗? (最好不要过多改变类型。)

1 个答案:

答案 0 :(得分:5)

警告:我还没有测试过这段代码。

对我来说最干净的方法是遵循Prelude.Extras式的路径:

class NFData1 f where
  rnf1 :: NFData a => f a -> ()

现在,您可以为每种矢量类型编写类似

的内容
instance NFData1 V where
  rnf1 = rnf

然后

instance (NFData1 v, NFData a) => NFData (DenseIntMap v a) where ...

可能更适合您当前代码的替代方法是明确地将v视为Vector。而不是担心v a更愿意强迫自己,而是通过折叠将你自己的想法压在喉咙上:像

instance (Vector v a, NFData a) => NFData (DenseIntMap v a) where
  rnf = V.foldl' (\() e -> rnf e) ()

第二种方法似乎很可能在矢量融合方面表现不佳,除非你要注意哪些矢量要从左到右,从右到左强制。