Skip to content

Instantly share code, notes, and snippets.

@janesser
Created December 22, 2016 00:27
Show Gist options
  • Save janesser/d7752548c3eee9bfa0a42db1f0b46763 to your computer and use it in GitHub Desktop.
Save janesser/d7752548c3eee9bfa0a42db1f0b46763 to your computer and use it in GitHub Desktop.
navigation tree with prolog
child(n1, [n11, n12]).
child(n11, [c11, c2]).
child(n12, [c11]).
child(c1, [c11, c12]).
child(c11, [p111, p112]).
child(c12, [p112]).
% distributive
is_child(A, B) :- child(A,KIDS), member(B, KIDS).
% transitive
is_child(A, C) :- is_child(A,B), is_child(B,C).
% upwards
is_root(A, _root) :- parents(A, P), length(P, L), L = 0 -> _root = true ; _root = false.
parents(A, _parents) :- findall(_parents, (child(_parents, B), member(A, B)), _parents).
parent(A, _parent) :- parents(A, P), nth1(1, P, _parent, _).
path_to_root(A, _path) :-
is_root(A, _root), _root ->
_path = A;
parent(A,B), path_to_root(B, C), append([A], C, _path).
% downwards
children(A, _children) :- findall(Y, child(A, Y), Y), flatten(Y, _children).
%% pre-order
tree(A, _tree) :-
children(A, B),
maplist(tree, B, C),
append([A], C, _tree).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment