Here is my implementation of flatten/2
:
flt([], []).
flt([H|L], [H|X]):-
not(is_list(H)),
flt(L, X).
flt([H|L], X):-
append(R, F, X),
flt(H, R),
flt(L, F).
The expected result is given:
?- flt([1,[2,3,[4,5],6],7], X).
X = [1, 2, 3, 4, 5, 6, 7]
However, when I hit ;
the stack limit is exceeded. Why does this happen? Where is the infinite recursion?
Thanks.
The problem is that you call
append(R, F, X)
with only uninstantiated variables.There is only one solution for
flt(+List, -Flatlist)
. However, on backtracking,append(R, F, X)
is tried again and again and again without ever finding another solution...You can test this by asking
The solution is to rearrange the goals in your third clause:
This is a very good example for the fact that Prolog is not purely declarative, since its implementation of resolution by simple chronological backtracking forces procedural features on the language.
To illustrate the problem, have a look at this trace (where I skipped a lot in order to just emphasize the loop problem):
This drawing shows it graphically. What happens after asking for an additional answer is colored red.
Another possible solution is to add cuts: