Question

Write a predicate that returns the second to last element in a list.

Prolog

Write a predicate that returns the second to last element in a list. 


?- second last clement(x, [a.b.c.d,e] 

x = d

?- second last element (X, []) 

false. 

?- second last element (3, [5,4,3,2,1])

true.

1 0
Add a comment Improve this question Transcribed image text
Answer #1

There are many ways to return a second to last item in a list.
1.
secondLast(L, X) :-
      append(_, [X, _], L).
This predicate can get you the second last item in a list.

2.
secondLast([X,_], X).
secondLast([_|T], X) :- secondLast(T, X).
This predicate also gets you the second last item in a list.
Here the first statement (secondLast([X,_], X).) says x is an element which is in a position of second to last in a list [X,_], which is true. _ means the last item which we dont need.
The second statement (secondLast([_|T], X) :- secondLast(T, X).) states that X is the second to last element of the list, T. This is also true of any list that is 3 or more elements.

Add a comment
Know the answer?
Add Answer to:
Write a predicate that returns the second to last element in a list.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT