diff --git a/Frederik/README.md b/Frederik/README.md index 4533f32698f321f04ed1498f6bf6d1356756798d..20bf5768da92e3847d518a67391100cf6ea34768 100644 --- a/Frederik/README.md +++ b/Frederik/README.md @@ -5,4 +5,5 @@ AI 1 - 2019/2020 --- * 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) diff --git a/Frederik/prolog/2019-11-04-trees.pl b/Frederik/prolog/2019-11-04-trees.pl new file mode 100644 index 0000000000000000000000000000000000000000..2c22b600fd268224e27ed66b88642b8219579136 --- /dev/null +++ b/Frederik/prolog/2019-11-04-trees.pl @@ -0,0 +1,61 @@ +% 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. +