我有以下代码:
type Drawable = '["object" ::: Object, "transform" ::: M44 GL.GLfloat]
objXfrm :: "transform" ::: M44 GL.GLfloat
objXfrm = Field
objRec :: "object" ::: Object
objRec = Field
drawObject :: (Drawable `ISubset` a) => M44 GL.GLfloat -> PlainRec a -> IO ()
drawObject camera obj =
withVAO vao $ do
GL.currentProgram $= Just (program shdr)
setUniforms shdr (modelView =: (rGet objXfrm obj !*! camera))
GL.polygonMode $= (GL.Line, GL.Line)
GL.drawElements GL.Triangles inds GL.UnsignedInt nullPtr
where Object {objVAO = vao, objNumIndices = inds, objShader = shdr}
= rGet objRec obj
当我摆脱drawObject
上的类型时,它编译得很好,但是我得到的类型
Could not deduce (IElem * ("transform" ::: V4 (V4 GL.GLfloat)) a)
arising from a use of `rGet'
from the context (ISubset * Drawable a)
...
Could not deduce (IElem * ("object" ::: Object) a)
arising from a use of `rGet'
from the context (ISubset * Drawable a)
GHC为我推断的类型是
drawObject
:: (IElem * ("object" ::: Object) rs,
IElem * ("transform" ::: V4 (V4 GL.GLfloat)) rs) =>
V4 (V4 GL.GLfloat)
-> Rec rs Data.Functor.Identity.Identity -> IO ()
作为类型签名,它可以正常工作,但ISubset
的签名则不行。如果我将参数交换为ISubset
,则错误完全相同。这是怎么回事?
答案 0 :(得分:3)
查看Vinyl的源代码,IElem x xs
(Implicit (Elem x xs)
的同义词)有两个实例:
instance Implicit (Elem x (x ': xs)) where
implicitly = Here
instance Implicit (Elem x xs) => Implicit (Elem x (y ': xs)) where
implicitly = There implicitly
请注意,此处未提及Subset
。逻辑上,(x ∈ xs) ∧ (xs ⊆ ys) ⇒ (x ∈ ys)
,但由于没有签名Implicit (Subset xs ys), Implicit (Elem x xs) => Implicit (Elem x ys)
的实例,Haskell无法推断出适当的实例。此外,不能写这样的实例,因为这样做会导致一些讨厌的实例重叠。
作为一种可能的解决方法,我们可以直接操纵成员证人(Elem
和Subset
)以强制执行适当的实例(这完全未经测试,可能会失败):
{-# LANGUAGE RankNTypes, ScopedTypeVariables, and possibly more... #-}
-- Lift an Elem value to a constraint.
withElem :: Elem x xs -> (forall r. IElem x xs => r) -> r
withElem Here x = x
withElem (There e) x = withElem e x
-- Witness of (x ∈ xs) ⇒ (xs ⊆ ys) ⇒ (x ∈ ys)
subsetElem :: Elem x xs -> Subset xs ys -> Elem x ys
subsetElem Here (SubsetCons e _) = e
subsetElem (There e) (SubsetCons _ s) = There (subsetElem e s)
-- Utility for retrieving Elem values from Fields (:::).
fieldElem :: IElem x xs => x -> Elem x xs
fieldElem _ = implicitly
inSubset :: IElem x xs => x -> Subset xs ys -> (forall r. IElem x ys => r) -> r
inSubset f s x = withElem (subsetElem (fieldElem f) s) x
drawObject :: forall a. (Drawable `ISubset` a) => M44 GL.GLfloat-> PlainRec a -> IO ()
drawObject camera obj =
inSubset objRec subset $
inSubset objXfrm subset $
-- The desired instances should now be available here
...
where
subset = implicitly :: Subset Drawable a
...
答案 1 :(得分:2)
通过简要地查看Vinyl代码,似乎整个“子集”的想法还没有完全实现(意味着,它需要更多的功能和实例才能真正有用)。你能不能只使用记录之间的“子类型”关系?然后就可以了
drawObject :: (PlainRec a <: PlainRec Drawable) => M44 GL.GLfloat -> PlainRec a -> IO ()
drawObject camera obj' =
... -- as before
where
obj :: PlainRec Drawable
obj = cast obj'
... -- rest as before