Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Define the functions in prolog

Status
Not open for further replies.

aznxhung

Programmer
Apr 29, 2002
1
US
The whole question is define the following predicates in prolog:
1, lastelem(L,X) which is true only when X is the last element in the list L.

2, replast(L,X,M) which is true only when M is the same as L except(possibly) for the last element which is X for M.

3, exchfal(L,M) which is true only when M is the same as L except that the first element of L is the last element of M and vice versa. If either L or M is empty or has length 1, then they should be equal.

Here is a samle session:
| ?-lastelem([1,2,3,4],X).
X = 4 ?;
no

| ?-replast([1,2,3,4],5,Z)
Z =[1,2,3,5] ? ;
no

| ?-exchfal([1,2,3,4],U)
U =[4,2,3,1] ?;
no

| ?-exchfal([1,2,3,4,10],U)
U =[10,2,3,4,1] ? ;
no
 
Hello. No.1 is easy.

lastelem([X], X).
lastelem([_|R], X) :- lastelem(R, X).
 
No2 is ...

%% program %%%

replast([], _, []).
replast([L], X, [X]) :- !.
replast([L1|LS], X, [L1|M]) :- replast(LS, X, M).

%%% sample %%%

?- replast([10, 20, 30], 90, M).
M = [10,20,90] ;
no

?- replast([10], 90, M).
M = [90] ;
no

?- replast([], 90, M).
M = '[]' ;
no

?- replast([10, 20, 30], X, [10, 20, 90]).
X = 90 ;
no

?- replast(X, 90, [10, 20, 90]).
X = [10,20,H120] ;
no
 
And No.3 is ...

exchfal([], []).
exchfal([L1|LS], [W1|W2]) :-
lastelem([L1|LS], W1),
replast(LS, L1, W2).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top