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!

prolog list processing (SIMPLE) 1

Status
Not open for further replies.

toneydiscount

Programmer
Apr 24, 2010
1
US
Hello,
I am trying to become familiar with prolog and I am trying to do a simple compare of two lists.

For example, let's say that I provide two prolog facts:
list1([a,b,c]).
list2([w,x,y,z]).

Now how would I compare the two, I know there is length function but not sure how to use it.
Is it something like this?

Longer(List1, List2) :- length(List1, N) > length(List2, M).

So in this case it should return no becasue list2 is longer. Am I even close?
 
Prolog use predicates, not functions.
you can write longer (notice the small letter "l") like that
Code:
longer(L1, L2) :-
  length(L1, N1),
  length(L2, N2),
  N1 > N2.
But, if you use length to compare these lists, you will travel through these lists two times, but it can be done with only one travel :

Code:
% empty lists have the same longer so longer fails.
longer([], []) :- !, fail.

% when the first list is empty and not the second longer fails
longer([], _) :- ! fail.

% when the second list is empty, but not th first, longer succeeds.
longer(_, []) :- !.

% In the general case, we have just to test the lists without theire first element :
longer([_|T1], [_|T2]) :-
  longer(T1, T2).
The cut is necessary to stop backtraking.
You can see that we travel only one time through the lists, the program ends when the shortest list is finished.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top