I want it to be working like this so then d disappears etc.
?- remove_last_item([a,b,c,d], L).
L = [a, b, c] ?
Does anyone know how to do this as I got this line
but what other line should I add to this so then the
above can be achieved.
In Prolog usually, to understand the question is to have your answer already. So you need to define a predicate,
remove_last_item(A,B)such thatBisAwithout the last item. So what is list in Prolog? Like in Lisp, it is recursively defined on top of pairs, with special symbol – empty list – signifying the “end of list”.What does that mean? A pair,
'.'(A,B), obviously has two parts. The list[a,b,c,d]is then encoded as'.'(a,'.'(b,'.'(c,'.'(d,[])))). This can also be written as[a|[b,c,d]], or[a,b|[c,d]], or[a,b,c|[d]], or[a,b,c,d|[]]. Hereais what’s known as “head” and[b,c,d]a “tail” or “rest” of the list[a,b,c,d].So now we just write down what we want our predicate to say, from the simplest case up:
It reads, “removing last item from a singleton list leaves us with an empty list; removing last item from a list of more than one element means removing the last item from the rest of the list, coming after its head”.
edit: Another way to look at it is by “starting from the top”: writing down some equivalency “law”, which the predicate must follow:
We still don’t “know” what
remove_last_item“does”, we just wrote down an equivalency law that it must follow, right? But then it becomes the very definition itself that we’re after. Fleshing out all the suggestive names, it becomes the (familiar)So now we can recognize this as structural recursion over lists, and just add a termination clause, to add some “substance” to it.