Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a tree-like DAG in Haskell

How do you define a directed acyclic graph (DAG) (of strings) (with one root) best in Haskell?

I especially need to apply the following two functions on this data structure as fast as possible:

  1. Find all (direct and indirect) ancestors of one element (including the parents of the parents etc.).
  2. Find all (direct) children of one element.

I thought of [(String,[String])] where each pair is one element of the graph consisting of its name (String) and a list of strings ([String]) containing the names of (direct) parents of this element. The problem with this implementation is that it's hard to do the second task.

You could also use [(String,[String])] again while the list of strings ([String]) contain the names of the (direct) children. But here again, it's hard to do the first task.

What can I do? What alternatives are there? Which is the most efficient way?

EDIT: One more remark: I'd also like it to be defined easily. I have to define the instance of this data type myself "by hand", so i'd like to avoid unnecessary repetitions.

like image 801
Mekeor Melire Avatar asked May 06 '13 20:05

Mekeor Melire


People also ask

Can a tree be a DAG?

A Tree is just a restricted form of a Graph. Trees have direction (parent / child relationships) and don't contain cycles. They fit with in the category of Directed Acyclic Graphs (or a DAG). So Trees are DAGs with the restriction that a child can only have one parent.

How do you define a DAG?

What Does Directed Acyclic Graph (DAG) Mean? In computer science and mathematics, a directed acyclic graph (DAG) is a graph that is directed and without cycles connecting the other edges. This means that it is impossible to traverse the entire graph starting at one edge. The edges of the directed graph only go one way.

Is DAG a rooted directed tree?

A rooted tree is a tree with one vertex designated as the root. For a directed graph the edges are typically all directed toward the root or away from the root. Directed acyclic graphs. A directed graph with no cycles is a directed acyclic graph (DAG).

Is acyclic graph same as tree?

An acyclic graph is a graph having no graph cycles. Acyclic graphs are bipartite. A connected acyclic graph is known as a tree, and a possibly disconnected acyclic graph is known as a forest (i.e., a collection of trees).


1 Answers

Have you looked at the tree implemention in Martin Erwig's Functional Graph Library? Each node is represented as a context containing both its children and its parents. See the graph type class for how to access this. It might not be as easy as you requested, but it is already there, well-tested and easy-to-use. I have used it for more than a decade in a large project.

like image 184
tillmo Avatar answered Oct 01 '22 23:10

tillmo