let grwork = [("wake","shower"); ("shower","dress"); ("dress","go"); ("wake","eat"); ("eat","washup"); ("washup","go")];; let g1 = [("wake","shower"); ("shower","wake")];; let topsort0 graph = let rec nexts = function (x,[]) -> [] | (x,(a,b)::l) -> if a=x then b::nexts(x,l) else nexts(x,l) in let rec sort = function ([], visited) -> visited | (x::xs, visited) -> if List.mem x visited then sort(xs, visited) else sort(xs, sort(nexts(x,graph), x::visited)) (* Buggy! Compare below for correct versions *) in let rec firsts = function [] -> [] | (a,b)::pairlist -> a::(firsts pairlist) in sort(firsts graph, []) ;; let topsort1 graph = let rec nexts = function (x,[]) -> [] | (x,(a,b)::l) -> if a=x then b::nexts(x,l) else nexts(x,l) in let rec sort = function ([], visited) -> visited | (x::xs, visited) -> if List.mem x visited then sort(xs, visited) else sort(xs, x::sort(nexts(x,graph), visited)) in sort(List.map (fun (a,b) -> a) graph, []) ;; let topsort2 graph = let nexts(x,graph) = List.fold_right (@) (List.map (fun (a,b) -> if a=x then [b] else []) graph) [] in let rec sort = function ([], visited) -> visited | (x::xs, visited) -> if List.mem x visited then sort(xs, visited) else sort(xs, x::sort(nexts(x,graph), visited)) in sort(List.map (fun (a,b) -> a) graph, []) ;;