Dear Levan,
On Jun 10, 2009, at 9:25 AM, Levan Cheishvili wrote:
> I have the following structure:
>
> object('obj1', [id='12', color='blue']).
> object('obj4', [id='13', color='red', weight=120]).
> object('obj21', [id='15 a', color='yellow', weight=1000, price=23]).
> object('obj21', [id='16 a', color='blue', weight=200, price=230]).
>
> I have a predicate which finds all objects with particular key, e.g.
> objects with color='blue'.
> In many cases result will be list of objects.
> My question is:
> How to write a sorting predicate which will sort objects within a
> resulting list by one of one or many keys(id or/and price, etc...)
You define a predicate that states if an object should be ordered
before, after, or either before or after, another object.
Then you call predsort/3 with this comparison predicate as first
argument.
For example (perhaps not the most elegant or efficient way to do it...):
object_id_value(object(_,L), ID) :-
member((id=ID), L).
compare_objects_by_id(<, X, Y) :-
object_id_value(X, N),
object_id_value(Y, M),
sort([N,M], [N|_]).
compare_objects_by_id(>, X, Y) :-
object_id_value(X, N),
object_id_value(Y, M),
sort([N,M], [M|_]).
compare_objects_by_id(=, _, _).
?- predsort(compare_objects,
[
object('obj21', [id='16 a', color='blue', weight=200, price=230]),
object('obj1', [id='12', color='blue']),
object('obj21', [id='15', color='yellow', weight=1000, price=23]),
object('obj4', [id='13', color='red', weight=120])
],
[
object('obj1', [id='12', color='blue']),
object('obj4', [id='13', color='red', weight=120]),
object('obj21', [id='15', color='yellow', weight=1000, price=23]),
object('obj21', [id='16 a', color='blue', weight=200, price=230])
]).
true.
You can combine the keys and their values in any particular way in the
comparison predicate.
Cheers!
Willem
--
Dr. Willem Robert van Hage
Vrije Universiteit Amsterdam
wrvhage@... -
http://www.few.vu.nl/~wrvhage_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog