Skip to content

Add Graph.merge/2 for combining two graphs#89

Open
dannote wants to merge 1 commit intobitwalker:mainfrom
dannote:graph-merge
Open

Add Graph.merge/2 for combining two graphs#89
dannote wants to merge 1 commit intobitwalker:mainfrom
dannote:graph-merge

Conversation

@dannote
Copy link
Copy Markdown

@dannote dannote commented Apr 19, 2026

There's currently no way to combine two graphs without iterating over all vertices and edges of one and adding them to the other via the public API. This is both verbose and slow — each add_edge call does hash lookups and MapSet insertions individually.

Graph.merge/2 combines all vertices and edges from two graphs in a single operation by merging the underlying maps directly. This is useful when building a graph in parts (e.g. analyzing separate modules and combining the results, or merging independently constructed subgraphs into a whole).

When the same edge exists in both graphs (same vertex pair and label), the weight from the second graph wins — consistent with Map.merge/2 semantics. Same goes for vertex labels. Both graphs must be of the same type, otherwise an ArgumentError is raised.

g1 = Graph.new() |> Graph.add_edges([{:a, :b}, {:b, :c}])
g2 = Graph.new() |> Graph.add_edges([{:c, :d}, {:d, :e}])

g = Graph.merge(g1, g2)
Graph.dijkstra(g, :a, :e)
#=> [:a, :b, :c, :d, :e]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant