我正在尝试制作一个简单的图形结构,并编写了以下内容。但是 GHG 会引发错误,我就堆在那里。这是我第一次制作自己的类型类,所以也许我做错了什么。有人可以解释什么是错的吗?
我发现了一个类似的问题,但我认为它不适用于我的情况。: Error binding type variables in instance of typeclass
class Link l where
node :: (Node n) => l -> n
class Node n where
links :: (Link l) => n -> [l]
data (Node n) => SimpleLink n =
SimpleLink
{ simpleLinkNode :: n
} deriving (Show, Read, Eq)
instance (Node n) => Link (SimpleLink n) where
node = simpleLinkNode
data (Link l) => SimpleNode l =
SimpleNode
{ simpleNodeLinks :: [l]
} deriving (Show, Read, Eq)
instance (Link l) => Node (SimpleNode l) where
links = simpleNodeLinks
这是我收到的错误消息:
***.hs:13:10:Could not deduce (n ~ n1)
from the context (Node n)
bound by the instance declaration
at ***.hs:12:10-40
or from (Node n1)
bound by the type signature for
node :: Node n1 => SimpleLink n -> n1
at ***.hs:13:3-23
`n' is a rigid type variable bound by
the instance declaration
at ***.hs:12:16
`n1' is a rigid type variable bound by
the type signature for node :: Node n1 => SimpleLink n -> n1
at ***.hs:13:3
Expected type: SimpleLink n -> n1
Actual type: SimpleLink n -> n
In the expression: simpleLinkNode
In an equation for `node': node = simpleLinkNode
***.hs:21:11:Could not deduce (l ~ l1)
from the context (Link l)
bound by the instance declaration
at ***.hs:20:10-40
or from (Link l1)
bound by the type signature for
links :: Link l1 => SimpleNode l -> [l1]
at ***.hs:21:3-25
`l' is a rigid type variable bound by
the instance declaration
at ***.hs:20:16
`l1' is a rigid type variable bound by
the type signature for links :: Link l1 => SimpleNode l -> [l1]
at ***.hs:21:3
Expected type: SimpleNode l -> [l1]
Actual type: SimpleNode l -> [l]
In the expression: simpleNodeLinks
In an equation for `links': links = simpleNodeLinks
编辑 1
我尝试了丹尼尔的一些建议。但我无法让它们工作。
构造函数类
得到:“`n' 没有应用于足够的类型参数”
class Link l n where
node :: Node n l => l n -> n l
class Node n l where
links :: Link l n => n l -> [l n]
多参数类型类(MPTC)
得到:“在类声明中循环(通过超类)”
class (Node n) => Link l n where
node :: l -> n
class (Link l) => Node n l where
links :: n -> [l]
具有函数依赖关系的 MPTC
得到:“在类声明中循环(通过超类)”
class (Node n) => Link l n | l -> n where
node :: l -> n
class (Link l) => Node n l | n -> l where
links :: n -> [l]
目标(编辑 2)
我想要实现的是一个有向无环图结构,如下所示(更具体地说,是因子图)。
(来源:microsoft.com)
有两种节点(白色圆圈和红色正方形),它们只连接到不同类型的节点,这意味着有两种链接。
我想要不同版本的节点和链接,它们附加了数据(数组)。我还想要只有一种类型的节点和链接的“香草”DAG。但是为了遍历它们,我只想要一个接口来做到这一点。