我正在尝试使用generics-sop中的All来约束类型列表。
class (Typeable a) => TestClass (a :: k)
instance (Typeable a) => TestClass a
foo :: (All Typeable xs) => NP f xs -> z
foo = undefined
bar :: (All TestClass xs) => NP f xs -> z
bar = foo 这会产生错误
Could not deduce: Generics.SOP.Constraint.AllF Typeable xs
arising from a use of ‘foo’
from the context: All TestClass xsgenerics-sop文档指出
"All Eq‘Int,Bool,Char等同于约束(Eq Int,Eq Bool,Eq Char)
但在这种情况下,情况似乎并非如此,因为
foo2 :: (Typeable a, Typeable b) => NP f '[a,b] -> z
foo2 = undefined
bar2 :: (TestClass a, TestClass b) => NP f '[a,b] -> z
bar2 = foo2编译正常。
我的问题
1)这是预期的行为吗? 2)如果是,有什么解决方法吗?
我的用例是,我希望传递一个类型级别的类型列表,该列表由单个类名(如class (Typeable a, Eq a, Show a) => MyClass a)下的一组不同的类约束,但也可以调用不太专业的函数,这些函数只需要这些类的一些子集。
搜索结果是superclasses aren't considered,但我不认为这是这里的问题-我认为这与generics-sop中All约束的组合方式有关。
发布于 2018-06-10 04:24:52
All f xs实际上等同于(AllF f xs, SListI xs)。AllF是一个类型族:
type family AllF (c :: k -> Constraint) (xs :: [k]) :: Constraint where
AllF _ '[] = ()
AllF c (x:xs) = (c x, All c xs)你会发现它不能减少,除非xs在WHNF中,所以它就卡在你的情况下了。您可以使用mapAll
import Generics.SOP.Dict
mapAll :: forall c d xs.
(forall a. Dict c a -> Dict d a) ->
Dict (All c) xs -> Dict (All d) xs
-- ::ish forall f g xs. (forall a. f a -> g a) -> All f xs -> All g xs
-- stores a constraint in a manipulatable way
data Dict (f :: k -> Constraint) (a :: k) where
Dict :: f a => Dict f a
bar :: forall xs f z. (All TestClass xs) => NP f xs -> z
bar = case mapAll @TestClass @Typeable @xs (\Dict -> Dict) Dict of
Dict -> foo
-- TestClass a -> Typeable a pretty trivially:
-- match Dict to reveal TestClass a
-- put the Typeable part of the TestClass instance into another Dict
-- We already know All TestClass xs; place that into a Dict
-- mapAll magic makes a Dict (All Typeable) xs
-- match on it to reveal
-- foo's constraint is satisfiedhttps://stackoverflow.com/questions/50777865
复制相似问题