我正在尝试为Linear.V类型创建一个新类型包装器并派生有用的实例。我正在尝试这个:
{-# LANGUAGE DataKinds, PolyKinds, ScopedTypeVariables,
StandaloneDeriving, FlexibleContexts, UndecidableInstances,
GeneralizedNewtypeDeriving, PartialTypeSignatures, TypeFamilies #-}
import Linear.V
import Control.Lens.At
data Foo = Foo1 | Foo2 deriving (Show, Eq)
尝试 1 - 我认为 GeneralizedNewtypeDeriving 可以,但不:
newtype Bar n = Bar {
getBar :: V n Foo
} deriving (Show, Eq, Ixed)
我收到此错误:
• Couldn't match representation of type ‘f (V n Foo)’
with that of ‘f (Bar n)’
arising from the coercion of the method ‘ix’
from type ‘Index (V n Foo)
-> Control.Lens.Type.Traversal' (V n Foo) (IxValue (V n Foo))’
to type ‘Index (Bar n)
-> Control.Lens.Type.Traversal' (Bar n) (IxValue (Bar n))’
NB: We cannot know what roles the parameters to ‘f’ have;
we must assume that the role is nominal
• When deriving the instance for (Ixed (Bar n))
我使用这样的独立派生进行了尝试2:
newtype Bar n = Bar {
getBar :: V n Foo
} deriving (Show, Eq)
type instance Index (Bar n) = Int
type instance IxValue (Bar n) = Foo
deriving instance Ixed (V n Foo) => Ixed (Bar n)
但后来我得到了一个不同的错误:
• Couldn't match representation of type ‘f1 (V n Foo)’
with that of ‘f1 (Bar n)’
arising from a use of ‘GHC.Prim.coerce’
NB: We cannot know what roles the parameters to ‘f1’ have;
we must assume that the role is nominal
• In the expression:
GHC.Prim.coerce
@(Index (V n Foo)
-> Control.Lens.Type.Traversal' (V n Foo) (IxValue (V n Foo)))
@(Index (Bar n)
-> Control.Lens.Type.Traversal' (Bar n) (IxValue (Bar n)))
ix
In an equation for ‘ix’:
ix
= GHC.Prim.coerce
@(Index (V n Foo)
-> Control.Lens.Type.Traversal' (V n Foo) (IxValue (V n Foo)))
@(Index (Bar n)
-> Control.Lens.Type.Traversal' (Bar n) (IxValue (Bar n)))
ix
When typechecking the code for ‘ix’
in a derived instance for ‘Ixed (Bar n)’:
To see the code I am typechecking, use -ddump-deriv
In the instance declaration for ‘Ixed (Bar n)’
• Relevant bindings include
ix :: Index (Bar n)
-> Control.Lens.Type.Traversal' (Bar n) (IxValue (Bar n))
(bound at a.hs:12:1)
我不确定为什么实际上会发生这两个错误。这可以以某种方式完成吗?我对高级类型级别的功能没有那么丰富的经验,到目前为止我也无法真正手动编写这个特定的实例定义,所以我也认为这是一个解决方案。但我更愿意以deriving
某种方式使用该机制,因为它似乎更可重用。
编辑:我已经尝试过这个手动实例声明:
type instance Index (Bar n) = Int
type instance IxValue (Bar n) = Foo
instance Ixed (Bar n) where
ix i f (Bar v) = ix i f v
但这会产生以下错误:
• Couldn't match type ‘V n Foo’ with ‘Bar n’
Expected type: f (Bar n)
Actual type: f (V n Foo)
• In the expression: ix i f v
In an equation for ‘ix’: ix i f (Bar v) = ix i f v
In the instance declaration for ‘Ixed (Bar n)’
• Relevant bindings include
v :: V n Foo (bound at a.hs:14:15)
f :: IxValue (Bar n) -> f (IxValue (Bar n)) (bound at a.hs:14:8)
i :: Index (Bar n) (bound at a.hs:14:6)
ix :: Index (Bar n)
-> Control.Lens.Type.Traversal' (Bar n) (IxValue (Bar n))
(bound at a.hs:14:3)
在我看来,编译器无法弄清楚Index
两者的V n Foo
and Bar n
is Int
。但我不确定。