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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prolog and List

Status
Not open for further replies.

effatha

Technical User
Jan 13, 2010
2
PT
Hi,

I'm trying to implement an algorithm in Prolog, in which I have a list L = [b1, b2, b3] and facts of the genre Liga2 (b1, 5), Liga2 (b2, 1), Liga2 (b3, 3). My aim is to sort the list L according to the argument of Liga2, getting as a result L = [b2, b3, b5].

Anyone can help me?

Thanks
 
Hi. Thanks by your answer. I'm using LPA and not SWI-Prolog. LPA doesn't have a predicate like predsort. However i implemented the follow code:


ordena2(L,LO):-findall(t(N,X),(member(X,L),liga2(X,N)),LL),
sort(LL,LLS),extrai_bs2(LLS,LO).

extrai_bs2([],[]).
extrai_bs2([t(_,X)|L],[X|L1]):-extrai_bs2(L,L1).

 
If you want to implement your own sort you can do like that (the list is very small), for a quicksort, the idea is the same. :
Code:
selection([], L, L).

selection([H | T], L, LF) :-
	extract(H, T, H1, [], T1),
	selection(T1, [H1 | L], LF).

% extract the greatest number
extract(H, [], H, L, L).

extract(H1, [H2 | T], HF, LC, LF) :-

	% I get the value of H1 and H2
	liga2(H1, V1),
	liga2(H2, V2),

	(   V1 =< V2 ->
	    extract(H2, T, HF, [H1 | LC], LF);
	    extract(H1, T, HF, [H2 | LC], LF)).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top