I’m working through some Prolog tutorials (nothing better to do and I found out earlier this week I quite like programming, so I’m working through some paradigms) and got to an exercise asking me to write a predicate delete_from_list/3 which removes all given occurences from a list.
I’ve solved this as follows:
delete_from_list([], _, []).
delete_from_list([Ah|At], X, [Ah|Bt]) :- Ah \= X, !, delete_from_list(At, X, Bt).
delete_from_list([_|Ct], X, Bt) :- delete_from_list(Ct, X, Bt).
What I’m wondering though, and this might be more aesthetic than practical purpose. How would you guys do this in another way? And why?
This mostly to gain a broader understanding of ways of problem solving in prolog 🙂
For example, could this be done in 1 rule?
With an if-then-else this can be done more elegantly (no cut involved):
And note that the predicate is still tail-recursive, meaning it doesn’t allocate extra stack frames and uses a constant amount of memory apart from building up the
Resultlist.And yes, it can be done in one clause, but it’s not pretty: