[Haskell-cafe] fgl Data.Graph examples
gsan at stillpsycho.net
Fri May 16 08:13:24 EDT 2008
I'm new to this, but I'll give it a shot.
> import Data.Graph.Inductive
There are several ways to build a graph. Let's say, node labels are 'String's
and edge labels are 'Double's. Edge labels would be the weights.
> grs :: [Gr String Double]
The below four lines generate the same graph. From labeled nodes and edges:
> grs = [mkGraph [(2, "start"), (1, "end")] [(2, 1, 1.0)],
> insEdge (2, 1, 1.0) $ insNodes [(2, "start"), (1, "end")] empty,
> (, 2, "start", [(1.0, 1)]) & ((, 1, "end", ) & empty),
> buildGr [(, 2, "start", [(1.0, 1)]), (, 1, "end", )]]
Test graph equality:
> gr = head grs
> same = all (equal gr) (tail grs)
You can populate the graph using (&) and ins... functions while
using 'newNodes' to get a bunch of unused node indexes ('Node's) to avoid
collisions. Deleting nodes also delete all connected edges, but trying to
insert an edge to a non-existent node will create an exception. So nodes get
> grd = delNode 1 gr -- no problem
> grd' = insEdge (2, 1, 1.0) grd -- exception
There are some functions to work on edges. For instance, this divides all
weights on your graph by 2:
> gr2 = emap (/ 2) gr
This makes the graph undirected:
> gr2u = undir gr2
There are other map and fold functions. 'gfold' is very powerful. It all
depends on your motive though.
I don't think there is a straightforward way to tweak individual nodes and
edges other than using graph construction tools. Maybe someone could shed a
light on this.
More information about the Haskell-Cafe