Skip to content
Snippets Groups Projects
Commit 4b4d7350 authored by jfschaefer's avatar jfschaefer
Browse files

prolog tree stuff

parent 1b495d59
No related branches found
No related tags found
No related merge requests found
...@@ -5,4 +5,5 @@ AI 1 - 2019/2020 ...@@ -5,4 +5,5 @@ AI 1 - 2019/2020
--- ---
* 2019-10-28: `prolog/2019-10-28-tutorial.pl` (simple prolog exercises) * 2019-10-28: `prolog/2019-10-28-tutorial.pl` (simple prolog exercises)
* 2019-10-31: `prolog/2019-10-31-tutorial.pl` (simple prolog exercises) * 2019-10-31 (substition for Katja): `prolog/2019-10-31-tutorial.pl` (simple prolog exercises)
* 2019-11-04: `prolog/2019-11-04-trees.pl` (some simple tree exercises)
% Check that a tree is indeed a binary tree
% (as specified in the homework)
isbinary(nil).
isbinary(tree(N, X, Y)) :-
integer(N),
isbinary(X),
isbinary(Y).
% Helper predicate: get the maximum of two integers
% e.g max(2,7,X) results in X=7.
%
% ! is the cut operator.
% It tells prolog not to backtrack anymore.
% In this case, we want to ignore the second case,
% if the first case is applicable.
max(X,Y,X) :- X >= Y, !.
max(_,Y,Y).
% Get the largest node in a tree
% (assuming it only contains natural numbers)
treemax(nil, 0).
treemax(tree(N, X, Y), Result) :-
treemax(X, XRes),
treemax(Y, YRes),
max(XRes, YRes, XYRes),
max(XYRes, N, Result).
% Get the depth of a tree
treedepth(nil, 0).
treedepth(tree(_, X, Y), Depth) :-
treedepth(X, XDepth),
treedepth(Y, YDepth),
max(XDepth, YDepth, D),
Depth is D + 1.
% helper predicate: concatenate two lists
concatenate([], L, L).
concatenate([H|T], L, [H|TL]) :-
concatenate(T, L, TL).
% get the leaves of a binary tree
leaves(nil, []).
leaves(tree(N, nil, nil), [N]) :- !.
leaves(tree(N, X, Y), Result) :-
leaves(X, XL),
leaves(Y, YL),
concatenate(XL, YL, Result).
% compute the result of a formula (which you can think of as a tree).
% Example tree: plus(times(2,6), 7)
compute(SomeInt, SomeInt) :-
integer(SomeInt).
compute(times(X, Y), R) :-
compute(X, XRes),
compute(Y, YRes),
R is XRes * YRes.
compute(plus(X, Y), R) :-
compute(X, XRes),
compute(Y, YRes),
R is XRes + YRes.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment