This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
yap-6.3/CLPBN/clpbn/topsort.yap
vsc a4b79352d5 preliminary support for viterbi algorithm and HMMs
some code cleanups


git-svn-id: https://yap.svn.sf.net/svnroot/yap/trunk@1363 b08c6af1-5177-4d33-ba66-4b1c6b8b522a
2005-08-17 13:34:56 +00:00

28 lines
951 B
Prolog

:- module(topsort, [topsort/2]).
:- use_module(library(ordsets),
[ord_subtract/3]).
/* simple implementation of a topological sorting algorithm */
/* graph is as Node-[Parents] */
topsort([], []) :- !.
topsort(Graph0,Sorted) :-
add_parentless(Graph0, Sorted, IncludedI, Graph1, SortedRest),
sort(IncludedI, Included),
delete_parents(Graph1, Included, NoParents),
topsort(NoParents, SortedRest).
add_parentless([], Sorted, [], [], Sorted).
add_parentless([Node-[]|Graph0], [Node|Sorted], [Node|Included], Graph1, SortedRest) :- !,
add_parentless(Graph0, Sorted, Included, Graph1, SortedRest).
add_parentless([Node|Graph0], Sorted, Included, [Node|Graph1], SortedRest) :-
add_parentless(Graph0, Sorted, Included, Graph1, SortedRest).
delete_parents([], _, []).
delete_parents([Node-Parents|Graph1], Included, [Node-NewParents|NoParents]) :-
ord_subtract(Parents, Included, NewParents),
delete_parents(Graph1, Included, NoParents).