DEPARTMENT OF ARTIFICIAL INTELLIGENCE Answers to Prolog exercises (#3) 1. flatten([],[]). flatten([[]|T], Tflat) :- flatten(T, Tflat). flatten([H|T], [H|Tflat]) :- atomic(H), !, flatten(T, Tflat). flatten([H|T], L) :- flatten(H, Hflat), flatten(T, Tflat), append(Hflat, Tflat, L). This uses 'append'. The second clause is there to remove empty lists (which are atomic). The cut is there in case of backtracking to the top level 'flatten' goal. 2. reverse([H|T], Rev) :- reverse(T, Trev), append(Trev, [H], Rev). This also uses 'append'. The version below is worth studying, even though it looks opaque at first; it is an example of a very generally useful technique. reverse(L,Reverse) :- rev3(L, [], Reverse). rev3([H|T], L, L2) :- rev3(T, [H|L], L2). rev3([], List, List). Note that it doesn't use 'append'. 3. chunk([], _). chunk([H|T], [H|T2]) :- starts(T, T2). chunk(List, [H|T2]) :- chunk(List, T2). starts([], _). starts([H|Rest], [H|Rest2]) :- starts(Rest, Rest2). The predicate 'starts' is there for when you have found the first element of the first list somewhere in the second. At that point you want to check that all the other elements of the first list immediately follow in the second. 4. Assuming declarations [1]: the first is illegal, because '^' has no right-hand expression of equal or lower priority the second is OK the third is OK Assuming declarations [2]: the first is OK the second is illegal because '@' has no right-hand expression of equal or lower priority the third is illegal because the expression in brackets is illegal; there, the operator '@' has no expressions on either side which are of equal or lower priority Sorry, there isn't space on this to fit tree diagrams of the OK ones...