hraban edited this page May 25, 2011 · 4 revisions
Clone this wiki locally

In a something-is-better-than-nothing spirit, here are some truly basic examples to get you started with cl-graph:

Loading cl-graph

This can be done in lots of ways, I will highlight one here that is particularly easy to get started with: using QuickLisp. Assuming you have it installed, execute the following:

(ql:quickload "cl-graph")

This will load cl-graph. We will rename the package for easy usage in the REPL:

(rename-package :cl-graph :g) ; Only do this for debugging and rapid prototyping

Usage examples

Undirected graph

;; Create a new graph
(setf u (g:make-graph 'g:graph-container))
;; Add some vertices
(setf foo (g:add-vertex u "foo"))
(setf bar (g:add-vertex u "bar"))
(setf baz (g:add-vertex u "baz"))
;; Edges
(g:add-edge-between-vertexes u foo bar)
(g:add-edge-between-vertexes u bar baz)
;; Retrieve information about the graph
(mapcar #'g:element (g:vertexes u)) ; => ("baz" "bar" "foo")
(g:edge-count u) ; => 2
(g:connected-graph-p u) ; => T
(g:adjacentp u foo bar) ; => T
(g:adjacentp u foo baz) ; => NIL
(g:iterate-vertexes u (lambda (v) (print (g:element v)))) ; => NIL (and prints the vertices to stdout)

Directed graphs

(setf z (g:make-graph 'g:graph-container :default-edge-type :directed))
(setf foo (g:add-vertex z "foo"))
(setf bar (g:add-vertex z "bar"))
(setf baz (g:add-vertex z "baz"))
;; Add the same edges, directed this time
(g:add-edge-between-vertexes z foo bar)
(g:add-edge-between-vertexes z bar baz)
;; Now let's use the direction
(g:graph-roots z) ; => (#<foo>)
(g:depth z) ; => 2
(g:child-vertexes foo) ; => (#<bar>)
(g:topological-sort z) ; => (#<foo> #<bar> #<baz>)