Question

In Prolog language, write a recursive predicate to find the last element of a list. You...

In Prolog language, write a recursive predicate to find the last element of a list. You may not use the built-in last predicate in your answer. E.g.,

?- lastEle(X,[how,are,you,today]).
X=today.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

%The basic idea is when there is only one element in a list that is our requirement and hence the base case.

%we recursively call on the remaining part of the list until this base case is reached.

%The following is the prolog code for the same.

lastEle(Y,[Y]).
lastEle(X,[Head|R]):-lastEle(X,R).

X GNU Prolog console File Edit Terminal Prolog Help GNU Prolog 1.4.5 (64 bits) Compiled Jul 14 2018, 12:58:46 with cl By Dani

%Please refer to the above image for execution on sample test cases.

%Please rate the solution. Also, don't hesitate to ask any doubts in the comments section below.

Add a comment
Know the answer?
Add Answer to:
In Prolog language, write a recursive predicate to find the last element of a list. You...
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