首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >超类都来自泛型-sop

超类都来自泛型-sop
EN

Stack Overflow用户
提问于 2018-06-10 03:38:14
回答 1查看 117关注 0票数 4

我正在尝试使用generics-sop中的All来约束类型列表。

代码语言:javascript
复制
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 

这会产生错误

代码语言:javascript
复制
Could not deduce: Generics.SOP.Constraint.AllF Typeable xs
  arising from a use of ‘foo’
  from the context: All TestClass xs

generics-sop文档指出

"All Eq‘Int,Bool,Char等同于约束(Eq Int,Eq Bool,Eq Char)

但在这种情况下,情况似乎并非如此,因为

代码语言:javascript
复制
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-sopAll约束的组合方式有关。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-10 04:24:52

All f xs实际上等同于(AllF f xs, SListI xs)AllF是一个类型族:

代码语言:javascript
复制
type family AllF (c :: k -> Constraint) (xs :: [k]) :: Constraint where
  AllF _ '[] = ()
  AllF c (x:xs) = (c x, All c xs)

你会发现它不能减少,除非xs在WHNF中,所以它就卡在你的情况下了。您可以使用mapAll

代码语言:javascript
复制
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 satisfied
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50777865

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档