| 1 | package graph |
| 2 | |
| 3 | // Traits represents a set of graph traits and types, such as directedness or acyclicness. These |
| 4 | // traits can be set when creating a graph by passing the corresponding functional options, for |
| 5 | // example: |
| 6 | // |
| 7 | // g := graph.New(graph.IntHash, graph.Directed()) |
| 8 | // |
| 9 | // This will set the IsDirected field to true. |
| 10 | type Traits struct { |
| 11 | IsDirected bool |
| 12 | IsAcyclic bool |
| 13 | IsWeighted bool |
| 14 | IsRooted bool |
| 15 | PreventCycles bool |
| 16 | } |
| 17 | |
| 18 | // Directed creates a directed graph. This has implications on graph traversal and the order of |
| 19 | // arguments of the Edge and AddEdge functions. |
| 20 | func Directed() func(*Traits) { |
| 21 | return func(t *Traits) { |
| 22 | t.IsDirected = true |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // Acyclic creates an acyclic graph. Note that creating edges that form a cycle will still be |
| 27 | // possible. To prevent this explicitly, use PreventCycles. |
| 28 | func Acyclic() func(*Traits) { |
| 29 | return func(t *Traits) { |
| 30 | t.IsAcyclic = true |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | // Weighted creates a weighted graph. To set weights, use the Edge and AddEdge functions. |
| 35 | func Weighted() func(*Traits) { |
| 36 | return func(t *Traits) { |
| 37 | t.IsWeighted = true |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | // Rooted creates a rooted graph. This is particularly common for building tree data structures. |
| 42 | func Rooted() func(*Traits) { |
| 43 | return func(t *Traits) { |
| 44 | t.IsRooted = true |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // Tree is an alias for Acyclic and Rooted, since most trees in Computer Science are rooted trees. |
| 49 | func Tree() func(*Traits) { |
| 50 | return func(t *Traits) { |
| 51 | Acyclic()(t) |
| 52 | Rooted()(t) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // PreventCycles creates an acyclic graph that prevents and proactively prevents the creation of |
| 57 | // cycles. These cycle checks affect the performance and complexity of operations such as AddEdge. |
| 58 | func PreventCycles() func(*Traits) { |
| 59 | return func(t *Traits) { |
| 60 | Acyclic()(t) |
| 61 | t.PreventCycles = true |
| 62 | } |
| 63 | } |