[英]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 谓词来做。
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
: X
是Y
的最后一部分,如果有东西可以与X
合并得到Y
:
last(X,Y) :- list_merge( _, X, Y ).
Note that last is already defined in swi-prolog, and here is its code .请注意last 已经在 swi-prolog 中定义, 这里是它的代码。
Here is a corrected version of your last
:这是您
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:它有两个问题:
?- last_play(E, [1]).
false.
?- 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]
.上面的链接代码没有这些问题,因为它在
[]
和[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".根据“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".您可以对“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].
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.