我对功能依赖性有疑问。我的理解是,例如,如果我写class Graph g a b | g -> a, g -> b
,那么任何特定的g
都只能与a
和b
中的一种类型相关联。实际上,尝试使用相同的g
和不同的a
和b
声明两个实例不起作用。
但是,编译器(ghc)似乎无法在以下情况下使用依赖项
class (Eq a, Eq b) => Graph g a b | g -> a, g -> b where
edges :: g -> [b]
src :: g -> b -> a
dst :: g -> b -> a
vertices :: g -> [a]
vertices g = List.nub $ map (src g) (edges g) ++ map (dst g) (edges g)
class Graph g a b => Subgraph g a b | g -> a, g -> b where
extVertices :: g -> [b]
data Subgraph1 g where
Subgraph1 :: Graph g a b => g -> [b] -> Subgraph1 g
instance Graph g a b => Graph (Subgraph1 g) a b where
vertices (Subgraph1 g _) = vertices g
edges (Subgraph1 g _) = edges g
src (Subgraph1 g _) = src g
dst (Subgraph1 g _) = dst g
如果我通过将参数Subgraph1
和a
添加到类型签名来修改b
,那么一切都会成功。
data Subgraph1 g a b where
Subgraph1 :: Graph g a b => g -> [b] -> Subgraph1 g a b
答案 0 :(得分:4)
不要使用fundeps,它们太痛苦了。使用相关类型。
class (Eq (Vertex g), Eq (Edge g)) => Graph g where
type Edge g :: *
type Vertex g :: *
edges :: g -> [Edge g]
src :: g -> Edge g -> Vertex g
dst :: g -> Edge g -> Vertex g
vertices :: g -> [Vertex g]
vertices g = nub $ map (src g) (edges g) ++ map (dst g) (edges g)
class Graph g => Subgraph g where
extVertices :: g -> [Edge g]
data Subgraph1 g where
Subgraph1 :: Graph g => g -> [Edge g] -> Subgraph1 g
instance Graph g => Graph (Subgraph1 g) where
type Edge (Subgraph1 g) = Edge g
type Vertex (Subgraph1 g) = Vertex g
vertices (Subgraph1 g _) = vertices g
edges (Subgraph1 g _) = edges g
src (Subgraph1 g _) = src g
dst (Subgraph1 g _) = dst g
这看起来更具可读性。 Edge g
是g
的边缘等类型。
请注意,我是机械翻译代码的,而不了解Subgraph1的功能。为什么在这里需要GADT,数据构造函数的第二个参数意味着什么?它不会在任何地方使用。