Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.27 KB | None | 0 0
  1. (* Implementation for "topol.mli" *)
  2. (* Author: Piotr Wojtczak *)
  3. (* Code review by Maciej Nadolski *)
  4.  
  5.  
  6. open PMap
  7.  
  8.  
  9. (* Exception thrown when the given graph is not acyclic *)
  10.  
  11. exception Cykliczne
  12.  
  13.  
  14. (* Function creating a functional map  *)
  15. (* structure from given adjacency list *)
  16.  
  17. let mapify l =
  18.     let create a v = add v (0, []) a in
  19.     let aux a (node, v) = List.fold_left create (add node (0, []) a) v in
  20.     let base = List.fold_left aux empty l
  21.     and attach = fun acc (node, children) ->
  22.                     let old = snd (find node acc) in
  23.                     add node (0, children @ old) acc in
  24.     List.fold_left attach base l
  25.    
  26.    
  27. (* Depth first search of a given graph          *)
  28. (* While traversing it also sorts the vertices  *)
  29. (* topologically and puts them in a list        *)
  30.  
  31. let rec dfs (acc, graph) node =
  32.     match find node graph with
  33.     | 1, _          -> raise Cykliczne
  34.     | 2, _          -> (acc, graph)
  35.     | 0, children   -> let new_acc, new_graph =
  36.                     List.fold_left dfs (acc, add node (1, children) graph) children in
  37.                     (node::new_acc, add node (2, children) new_graph)
  38.     | _, _          -> failwith "Uknown behavior"
  39.  
  40.  
  41. (* Function performing a topological sort over a given graph *)
  42.  
  43. let topol graph =
  44.     let unpacked = mapify graph in
  45.     fst (foldi (fun v _ a -> dfs a v) unpacked ([], unpacked))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement