简体   繁体   中英

Haskell Generating graphs with QuickCheck properties

Graphs have these properties:

The type 'Edge' represents an edge between two nodes.

data Edge v = Edge {source :: v, target :: v}
          deriving (Show,Eq,Ord)

The 'Graph' type represents a directed graph.

data Graph v = Graph {nodes :: Set v, edges :: Set (Edge v)}
           deriving Show

The fuction 'isDAG' tests if a graph is acyclic.

isDAG :: Ord v => Graph v -> Bool
isDAG g = isValid g && all nocycle (nodes g)
where nocycle v = all (\a -> v `notMember` reachable g a) $ Set.map target (adj g v)

The fuction 'isForest' tests if a valid DAG is a forest (a set of trees)

isForest :: Ord v => DAG v -> Bool
isForest g = isDAG g && all (\v -> length (adj g v) <= 1) (nodes g)

The generators code is:

DAGs generator

dag :: (Ord v, Arbitrary v) => Gen (DAG v)
dag = arbitrary `suchThat` isDAG

Forests generator

forest :: (Ord v, Arbitrary v) => Gen (Forest v)
forest = arbitrary `suchThat` isForest

I want to improve the generators Dag and Forest, so they are defined based on their properties and not with 'suchThat'. How can I do it?

Thank you in advance.

I believe the question at the core is how to generate DAGs and forests.

What's a forest? Forest is a collection of trees. What's a tree? Tree is a graph where every node except the root has exactly one parent. How do we turn it into an algorithm? Generate a list of nodes. For every node in the list going from the left randomly pick an element to the right of it as its parent and create an edge to it.

What is a DAG? DAG is a directed acyclic graph. What can we do with DAGs? We can topologically order them. What does that mean? It means we can put them in a sequence where every edge goes from left to right. How do we turn it into an algorithm? Generate a list of nodes. For every node in the list going from the left randomly pick a subset of elements to the right of it and create an edge to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM