[A] graph is a structure amounting to a set of objects in which some pairs of the objects are in some sense “related”.
A graph
Gconsists of a setE(G)of edges and a (disjoint) setV(G)of vertices, together with a relation of incidence which associates with each edge two vertices, not necessarily distinct, called its ends.
So we have objects (nodes and edges) and a relationship (incidence).
data Graph nodes edges
= Gr (Graph {nodes | edges}
incidence)fibs = 1 : 1 : zipWith (+) fibs
(tail fibs)Can we use tying the knot at the conceptual/data structural level?
new == existing| Theoretical | Vertices | Arcs |
| Existing graph structure | Nodes | Edges |
| New graph structure | Objects | Relationships |
class Graph g where
type Vertex g
type Arc g
vertices :: g -> Set (Vertex g)
arcs :: g -> Set (Arc g)
incident :: g -> Vertex g -> Set (Arc g)
ends :: g -> Arc g -> Set (Vertex g)instance Graph (GrEx node edge) where
type Vertex (GrEx node edge) = node
type Arc (GrEx node edge) = edge
...data Node object relationship a where
Object :: object -> Node Object
Relationship :: relationship
-> Node Relationship
getO :: Node o r a -> Maybe o
getR :: Node o r a -> Maybe rdata Edge = Edge (Node Object)
(Node Relationship)
newtype GrNew object relationship
= GrNew (GrEx (Node object relationship)
Edge)instance Graph (GrNew o r) where
type Vertex (GrNew o r) = o
type Arc (GrNew o r) = r
vertices = mapMaybe getO . vertices
arcs = mapMaybe getR . vertices
incident g = mapMaybe getR . incident g
. Object
ends g = mapMaybe getO . incident g
. Relationshipdata Edge = Edge (Node Object)
(Node Relationship)G = (object | relationship) + edgesG = objects + relationships + edgesedges set?incident and ends methods.objects and relationships?Sets into dictionaries.Node type.type Edge = (Node, Node)
(Node, Node).data Simple node
= Gr (Set node) (Set (node, node))
instance Graph (Simple node) where
type Vertex (Simple node) = node
type Arc (Simple node) = (node, node)
...Adds the following functions:
vertex :: Vertex g -> g
overlay :: g -> g -> g
connect :: g -> g -> gvertex n = Gr (singleton n) empty-- Graph union
overlay (Gr n1 e1) (Gr n2 e2)
= Gr (n1 `union` n2)
(e1 `union` e2)-- As with overlay,
-- but add edges from n1 to n2
connect (Gr n1 e1) (Gr n2 e2)
= Gr (n1 `union` n2)
(e1 `union` e2
`union` (zip n1 n2))