Commit 4b4d7350 authored by jfschaefer's avatar jfschaefer

prolog tree stuff

parent 1b495d59
......@@ -5,4 +5,5 @@ AI 1 - 2019/2020
* 2019-10-28: `prolog/` (simple prolog exercises)
* 2019-10-31: `prolog/` (simple prolog exercises)
* 2019-10-31 (substition for Katja): `prolog/` (simple prolog exercises)
* 2019-11-04: `prolog/` (some simple tree exercises)
% Check that a tree is indeed a binary tree
% (as specified in the homework)
isbinary(tree(N, X, 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, !.
% 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) :-
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.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment