Should I avoid tail recursion in Prolog and in general?

Short answer: Tail recursion is desirable, but don’t over-emphasize it. Your original program is as tail recursive as you can get in Prolog. But there are more important issues: Correctness and termination. In fact, many implementations are more than willing to sacrifice tail-recursiveness for other properties they consider more important. For example steadfastness. But your … Read more

Explanation of a Prolog algorithm to append two lists together

First, let’s translate the clauses into something more understandable: append([], List, List) :- !. can be written append([], List2, Result) :- Result = List2, !. and append([H|L1], List2, [H|L3]) :- append(L1, List2, L3). can be written append(List1, List2, Result) :- List1 = [Head1 | Tail1], Result = [HeadR | TailR], Head1 = HeadR, append(Tail1, List2, … Read more

tail-recursive function appending element to list

The following is an implementation of tail recursion modulo cons optimization, resulting in a fully tail recursive code. It copies the input structure and then appends the new element to it, by mutation, in the top-down manner. Since this mutation is done to its internal freshly-created data, it is still functional on the outside (does … Read more