1

我有一个关于功能依赖的问题。我的理解是,例如,如果我写class Graph g a b | g -> a, g -> b,那么任何特定g的都只能与一种类型相关联ab。事实上,试图声明两个实例相同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通过添加参数ab类型签名来进行修改,那么一切都会成功。

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

1 回答 1

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,数据构造函数的第二个参数是什么意思?它不在任何地方使用。

于 2011-07-23T09:29:37.293 回答