Reputation:
I have an assignment question like so:
Write a program to find the last element of a list. e.g.
?- last(X, [how, are, you]).
X = you
Yes
I'm currently finding the last element like this:
last([Y]) :-
write('Last element ==> '),write(Y).
last([Y|Tail]):-
last(Tail).
And it works. My question is, how do I change it to accept and set the addition X parameter and set it correctly?
I tried this, but it's not working ...
last(X, [Y]) :-
X is Y.
last(X, [Y|Tail]):-
last(X, Tail).
Upvotes: 0
Views: 1891
Reputation: 103
Using the unification operator is not the preferred way to unify in a case like this. You can use unification in a much more powerful way. See the following code:
last(Y, [Y]). %this uses pattern matching to Unify the last part of a list with the "place holder"
%writing this way is far more concise.
%the underscore represents the "anonymous" element, but basically means "Don't care"
last(X, [_|Tail]):-
last(X, Tail).
Upvotes: 1
Reputation: 3180
Most obvious problem: (is)/2
works with numbers only. (link)
-Number is +Expr True when Number is the value to which Expr evaluates
You want to use the unification operator (=)/2
(link):
last(X, [Y]) :-
X = Y,
!.
last(X, [_|Tail]):-
last(X, Tail).
Let's try:
?- last(X, [1, 2, 3]).
X = 3.
?- last(X, [a, b, c]).
X = c.
Upvotes: 1