submit itec380-01 p1.P
Write the following Prolog predicates:
last(List, TheLast) % 40 points nextToLast(List, TheNextToLast) % 35 points lastTwoReversed(List, TheLastTwo) % 15 points reverseLastTwo(List, NewList) % 10 points
Predicate last
succeeds if TheLast
is the last
element of List
and nextToLast
succeeds if
TheNextToLast
is the next to last element of List
.
If either element does not exist, then the predicate fails. In other
words, both fail if List
is empty and nextToLast
also fails if the list is of length one.
Predicate lastTwoReversed
succeeds if the TheLastTwo
is the list
containing exactly two elements: the last two elements of List
, but in reverse order.
It fails List
is a list with 0 or 1 elements.
Predicate reverseLastTwo
succeeds if the NewList
is a list
that is identical to List
, except that the last two elements are reversed.
It fails List
is a list with 0 or 1 elements.
All predicates fail if the first argument is not a list (unless, of course, it is a variable).
Here are some examples:
last([1,2,3], 3). Yes last([1,2,3], 4). No last([1,2,3], Y). Y=3 last([], Y). No last(Y, 3). Y=[3]. nextToLast([1,2,3], 2). Yes nextToLast([1,2,3], 3). No nextToLast([1,2,3], Y). Y=2 nextToLast([1], Y). No nextToLast(Y, 3). Y=[3, _h114]. % does not have to be 114 lastTwoReversed([1,2,3], Y). Y=[3,2] lastTwoReversed([1], Y). No reverseLastTwo([1,2,3,4], Y). Y=[1,2,4,3] reverseLastTwo([1,2], Y). Y=[2,1] reverseLastTwo([1], Y). No
Note that xsb Prolog contains several list functions which you are NOT to use for this assignment. If you need a list function, then you should simply write it yourself.
This assignment can be done relatively easily by reversing the list and then operating on it, and if necessary reversing the results. Please note that this method of solution will not earn full marks for the assignment. Of course, you can try this method as you are figuring out how to do the assignment, but if you want full credit for what you do, you should not use reverse in your solution.
Please be certain to use these exact names. I will not grade your program if your names are not exactly correct. Also, make sure that you do not mix up the names.
Please make sure that you test your program completely.
You may use any prolog system to write your program, but you should test it on xsb on rucs which is where I will run it for grading. Several free versions on prolog are available for download, including xsb and jlog.
Your program should follow good style. In this case this means to use white space to make your program easier to understand and to choose meaningful variable names. You should also include comments to make the code easier to understand as well as a header comment describing you, the project, etc.
Put your predicates in a file called p1.P
, and
use the command
submit itec380-01 p1.P
to turn it in. Remember that you must be on rucs
or one of its clients for submit to work correctly.