简体   繁体   中英

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

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?

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 ).

Note that last is already defined in swi-prolog, and here is its code .

Here is a corrected version of your last :

last_play(Last, [_|[Last]]).
last_play(Last, [_|T]) :-
    last_play(Last, T).

Results:

?- last_play(E, L).
L = [_, E] ;
L = [_, _, E] ;
L = [_, _, _, E] ;
L = [_, _, _, _, E] ;
L = [_, _, _, _, _, E]

There's 2 problems with it:

  1. It fails for a list containing a single element:
?- last_play(E, [1]).
false.
  1. It leaves an unwanted choicepoint:
?- last_play(E, [1,2,3]).
E = 3 ;
false.

The linked code above has neither of these problems, because it uses first-argument indexing on [] vs [Head|Tail] .

?- last([1], E).
E = 1.

?- last([1,2,3], E).
E = 3.

Your code is definitely not working according to the expected behavior of "last". This is what I see:

?- last(Last, [a,b,c,d]).
Last = [b, c, d] ;
Last = [c, d] ;
Last = [d] ;
Last = [] ;
false.

Is this really what you intended?

The solution in the other answer just repeats the same answers.

Here is how you could have defined "last" (... element of a list)

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

This works (try it.) even if it isn't optimal.

To get the last element of a list using "append" in the other direction, you should type:

?- append(_Front, [Last], List).

You can do exactly the same with your "list_merge". However "merge" also has a different expected behavior. You'd expect:

?- merge([b,m,x], [a,n,y], Merged).
Merged = [a,b,m,n,x,y].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM