yog/model
Core graph data structures and basic operations for the yog library.
This module defines the fundamental Graph type and provides all basic operations
for creating and manipulating graphs. The graph uses an adjacency list representation
with dual indexing (both outgoing and incoming edges) for efficient traversal in both
directions.
Graph Types
- Directed Graph: Edges have a direction (one-way relationships)
- Undirected Graph: Edges are bidirectional (mutual relationships)
Type Parameters
node_data: The type of data stored at each node (e.g.,String,City,Task)edge_data: The type of data stored on edges, typically weights (e.g.,Int,Float)
Quick Start
import yog/model
let assert Ok(graph) =
model.new(model.Undirected)
|> model.add_node(1, "Alice")
|> model.add_node(2, "Bob")
|> model.add_edge(from: 1, to: 2, with: 10) // weight = 10
Design Notes
The dual-map representation enables O(1) edge existence checks and O(1) transpose operations, at the cost of increased memory usage and slightly more complex edge updates.
Types
A simple graph data structure that can be directed or undirected.
node_data: The type of data stored at each nodeedge_data: The type of data (usually weight) stored on each edge
pub type Graph(node_data, edge_data) {
Graph(
kind: GraphType,
nodes: dict.Dict(Int, node_data),
out_edges: dict.Dict(Int, dict.Dict(Int, edge_data)),
in_edges: dict.Dict(Int, dict.Dict(Int, edge_data)),
)
}
Constructors
The type of graph: directed or undirected.
pub type GraphType {
Directed
Undirected
}
Constructors
-
DirectedA directed graph where edges have a direction from source to destination.
-
UndirectedAn undirected graph where edges are bidirectional.
Values
pub fn add_edge(
graph: Graph(n, e),
from src: Int,
to dst: Int,
with weight: e,
) -> Result(Graph(n, e), String)
Adds an edge to the graph with the given weight.
For directed graphs, adds a single edge from src to dst.
For undirected graphs, adds edges in both directions.
Returns Error if either endpoint node doesn’t exist in graph.nodes.
Use add_edge_ensure to auto-create missing nodes with a default value,
or add_node to explicitly add nodes before adding edges.
Example
graph
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_edge(from: 1, to: 2, with: 10)
// => Ok(graph)
graph
|> model.add_edge(from: 1, to: 2, with: 10)
// => Error("Node 1 does not exist")
pub fn add_edge_ensure(
graph: Graph(n, e),
from src: Int,
to dst: Int,
with weight: e,
default default: n,
) -> Graph(n, e)
Ensures both endpoint nodes exist, then adds an edge.
If src or dst is not already in the graph, it is created with
the supplied default node data before the edge is added. Nodes
that already exist are left unchanged.
Always succeeds and returns a Graph (never fails).
Example
// Nodes 1 and 2 are created automatically with data "unknown"
model.new(model.Directed)
|> model.add_edge_ensure(from: 1, to: 2, with: 10, default: "unknown")
// Existing nodes keep their data; only missing ones get the default
model.new(model.Directed)
|> model.add_node(1, "Alice")
|> model.add_edge_ensure(from: 1, to: 2, with: 5, default: "anon")
// Node 1 is still "Alice", node 2 is "anon"
Future Improvements
A future version may support separate defaults for each endpoint
(default_from and default_to). If you need this feature, please
open an issue.
For now, if you need different node values, then call add_node before
adding edges. Or call add_edge_with() with a callback function
that fetches the value of the NodeId (i.e. from a dict, database, or identity)
pub fn add_edge_with(
graph: Graph(n, e),
from src: Int,
to dst: Int,
with weight: e,
by by: fn(Int) -> n,
) -> Graph(n, e)
Ensures both endpoint nodes exist using a callback, then adds an edge.
If src or dst is not already in the graph, it is created by
calling the by function with the node ID to generate the node data.
Nodes that already exist are left unchanged.
Always succeeds and returns a Graph (never fails).
Example
// Nodes 1 and 2 are created automatically with value that's the same as NodeId
model.new(model.Directed)
|> model.add_edge_with(from: 1, to: 2, with: 10, by: fn(x) { x })
// Existing nodes keep their data; only missing ones get the default
model.new(model.Directed)
|> model.add_node(1, "1")
|> model.add_edge_with(from: 1, to: 2, with: 5, by: fn(n) { int.to_string(n) <> ":new" })
// Node 1 is still "1", node 2 is "2:new"
pub fn add_edge_with_combine(
graph: Graph(n, e),
from src: Int,
to dst: Int,
with weight: e,
using with_combine: fn(e, e) -> e,
) -> Result(Graph(n, e), String)
Adds an edge, but if an edge already exists between src and dst,
it combines the new weight with the existing one using with_combine.
The combine function receives (existing_weight, new_weight) and should
return the combined weight.
Returns Error if either endpoint node doesn’t exist in graph.nodes.
Time Complexity: O(1)
Example
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_edge(from: 1, to: 2, with: 10)
let assert Ok(graph) = model.add_edge_with_combine(graph, from: 1, to: 2, with: 5, using: int.add)
// Edge 1->2 now has weight 15 (10 + 5)
Use Cases
- Edge contraction in graph algorithms (Stoer-Wagner min-cut)
- Multi-graph support (adding parallel edges with combined weights)
- Incremental graph building (accumulating weights from multiple sources)
pub fn add_edges(
graph: Graph(n, e),
edges: List(#(Int, Int, e)),
) -> Result(Graph(n, e), String)
Adds multiple edges to the graph in a single operation.
Fails fast on the first edge that references non-existent nodes.
Returns Error if any endpoint node doesn’t exist.
This is more ergonomic than chaining multiple add_edge calls
as it only requires unwrapping a single Result.
Example
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_node(3, "C")
|> model.add_edges([
#(1, 2, 10),
#(2, 3, 5),
#(1, 3, 15),
])
pub fn add_node(
graph: Graph(n, e),
id: Int,
data: n,
) -> Graph(n, e)
Adds a node to the graph with the given ID and data. If a node with this ID already exists, its data will be replaced.
Example
graph
|> model.add_node(1, "Node A")
|> model.add_node(2, "Node B")
pub fn add_simple_edges(
graph: Graph(n, Int),
edges: List(#(Int, Int)),
) -> Result(Graph(n, Int), String)
Adds multiple simple edges (weight = 1) to the graph.
Fails fast on the first edge that references non-existent nodes. Convenient for unweighted graphs where all edges have weight 1.
Example
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_node(3, "C")
|> model.add_simple_edges([
#(1, 2),
#(2, 3),
#(1, 3),
])
pub fn add_unweighted_edges(
graph: Graph(n, Nil),
edges: List(#(Int, Int)),
) -> Result(Graph(n, Nil), String)
Adds multiple unweighted edges (weight = Nil) to the graph.
Fails fast on the first edge that references non-existent nodes. Convenient for graphs where edges carry no weight information.
Example
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_node(3, "C")
|> model.add_unweighted_edges([
#(1, 2),
#(2, 3),
#(1, 3),
])
pub fn all_nodes(graph: Graph(n, e)) -> List(Int)
Returns all node IDs in the graph. This includes all nodes, even isolated nodes with no edges.
pub fn edge_count(graph: Graph(n, e)) -> Int
Returns the number of edges in the graph.
For undirected graphs, each edge is counted once (the pair {u, v}). For directed graphs, each directed edge (u -> v) is counted once.
Time Complexity: O(V)
pub fn neighbors(graph: Graph(n, e), id: Int) -> List(#(Int, e))
Gets everyone connected to the node, regardless of direction. Useful for algorithms like finding “connected connectivity.”
pub fn new(graph_type: GraphType) -> Graph(n, e)
Creates a new empty graph of the specified type.
Example
let graph = model.new(Directed)
pub fn node_count(graph: Graph(n, e)) -> Int
Returns the number of nodes in the graph.
Equivalent to order(graph).
Time Complexity: O(1)
pub fn order(graph: Graph(n, e)) -> Int
Returns the number of nodes in the graph (graph order).
Time Complexity: O(1)
pub fn predecessors(
graph: Graph(n, e),
id: Int,
) -> List(#(Int, e))
Gets nodes you came FROM (Predecessors).
pub fn remove_edge(
graph: Graph(node_data, edge_data),
src: Int,
dst: Int,
) -> Graph(node_data, edge_data)
Removes a directed edge from src to dst.
For directed graphs, this removes the single directed edge from src to dst.
For undirected graphs, this removes the edges in both directions
(from src to dst and from dst to src).
Time Complexity: O(1)
Example
// Directed graph - removes single directed edge
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_edge(from: 1, to: 2, with: 10)
let graph = model.remove_edge(graph, 1, 2)
// Edge 1->2 is removed
// Undirected graph - removes both directions
let assert Ok(graph) =
model.new(Undirected)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_edge(from: 1, to: 2, with: 10)
let graph = model.remove_edge(graph, 1, 2)
// Edge between 1 and 2 is fully removed
pub fn remove_node(graph: Graph(n, e), id: Int) -> Graph(n, e)
Removes a node and all its connected edges (incoming and outgoing).
Time Complexity: O(deg(v)) - proportional to the number of edges connected to the node, not the whole graph.
Example
let assert Ok(graph) =
model.new(Directed)
|> model.add_node(1, "A")
|> model.add_node(2, "B")
|> model.add_node(3, "C")
|> model.add_edges([#(1, 2, 10), #(2, 3, 20)])
let graph = model.remove_node(graph, 2)
// Node 2 is removed, along with edges 1->2 and 2->3
pub fn successor_ids(graph: Graph(n, e), id: Int) -> List(Int)
Returns just the NodeIds of successors (without edge weights). Convenient for traversal algorithms that only need the IDs.
pub fn successors(graph: Graph(n, e), id: Int) -> List(#(Int, e))
Gets nodes you can travel TO (Successors).