帮助使用功能依赖

时间:2011-07-23 06:43:45

标签: haskell functional-dependencies

我对功能依赖性有疑问。我的理解是,例如,如果我写class Graph g a b | g -> a, g -> b,那么任何特定的g都只能与ab中的一种类型相关联。实际上,尝试使用相同的g和不同的ab声明两个实例不起作用。

但是,编译器(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

如果我通过将参数Subgraph1a添加到类型签名来修改b,那么一切都会成功。

data Subgraph1 g a b where
    Subgraph1 :: Graph g a b => g -> [b] -> Subgraph1 g a b

1 个答案:

答案 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 gg的边缘等类型。

请注意,我是机械翻译代码的,而不了解Subgraph1的功能。为什么在这里需要GADT,数据构造函数的第二个参数意味着什么?它不会在任何地方使用。