haskell – 如何从具有功能依赖性的类型类中获取和使用依赖类型
发布时间:2020-12-14 05:02:04 所属栏目:百科 来源:网络整理
导读:如何从具有功能依赖性的类型类中获取和使用依赖类型? 澄清并举例说明我最近的尝试(从我写的实际代码中最小化): class Identifiable a b | a - b where -- if you know a,you know b idOf :: a - binstance Identifiable Int Int where idOf a = af :: Iden
如何从具有功能依赖性的类型类中获取和使用依赖类型?
澄清并举例说明我最近的尝试(从我写的实际代码中最小化): class Identifiable a b | a -> b where -- if you know a,you know b idOf :: a -> b instance Identifiable Int Int where idOf a = a f :: Identifiable Int b => Int -> [b] -- Does ghc infer b from the functional dependency used in Identifiable,and the instance? f a = [5 :: Int] 但ghc似乎没有推断b,因为它打印出这个错误: Couldn't match expected type ‘b’ with actual type ‘Int’ ‘b’ is a rigid type variable bound by the type signature for f :: Identifiable Int b => Int -> [b] at src/main.hs:57:6 Relevant bindings include f :: Int -> [b] (bound at src/main.hs:58:1) In the expression: 5 :: Int In the expression: [5 :: Int] In an equation for ‘f’: f a = [5 :: Int] 对于上下文,这是一个较小的示例: data Graph a where Graph :: (Identifiable a b) => GraphImpl b -> Graph a getImpl :: Identifiable a b => Graph a -> GraphImpl b getImpl (Graph impl) = impl 这里的解决方法是将b作为类型arg添加到Graph: data Graph a b | a -> b where Graph :: (Identifiable a b) => GraphImpl b -> Graph a 完整的上下文:我有一个实体图表,每个实体都有一个id,每个实体都分配给1个节点.您可以按实体查找节点.我还有一个Graph’,它包含节点(可以分配一个实体),并查找一个节点,你需要提供节点的id,这是一个Int.图表在内部使用Graph’.我有一个IdMap,它将实体的id映射到Graph’中的节点ID.这是我的图表定义: data Graph a where Graph :: (Identifiable a b) => { _idMap :: IdMap b,_nextVertexId :: Int,_graph :: Graph' a } -> Graph a 答:使用类型系列,请参阅Daniel Wagner’s answer. 解决方法
GHC抱怨你在最顶层发布的最小f值确实有点奇怪.但它似乎适用于类型系列:
{-# LANGUAGE TypeFamilies #-} class Identifiable a where type IdOf a idOf :: a -> IdOf a instance Identifiable Int where type IdOf Int = Int idOf a = a f :: a -> [IdOf Int] f _ = [5 :: Int] 也许您可以将这个想法适应您的更大范例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |