Home > other >  Check if the given element is the last of an list or not
Check if the given element is the last of an list or not

Time:01-26

I have this predicate and this works.

last(X,[Y|X]).
last(X,[Y|Z]) :- last(X,Z).

But I also want to do it with my list_merge predicate.

list_merge([], X, X).
list_merge([X | L1], L2, [X | L3]) :-
   list_merge(L1, L2, L3).

How can I combine them?

CodePudding user response:

X is the last part of Y if there is something you can merge with X to get Y :

last(X,Y) :- list_merge( _, X, Y ).

CodePudding user response:

This is a better version of last, using [Head|Tail] notation with first-argument indexing, to prevent an unwanted choicepoint:

last_elem([H|T], Elem) :-
    last_elem_(T, H, Elem).

last_elem_([], Elem, Elem).
last_elem_([H|T], _, Elem) :-
    last_elem_(T, H, Elem).

Result:

?- last_elem([1,2,3], E).
E = 3.
  • Related