Levan Cheishvili writes:
> For example (perhaps not the most elegant or efficient way to do it...):
There are two common ways to define sorting. One is by defining a
comparison predicate, as you have done, and the other is mapping with
maplist/3 the list to a list of the form Key-Value, keysorting that
and mapping it back. To me, using keysort/2 is still the more natural
way - maybe because keysort/2 is more common. Also, ill defined
mappings result typically in a failure of the mapping - and not in
random results.
Your predicate compare_objects_by_id/3 can be generalized to
compare_objects_by/1 which illustrated the usage of continuations.
?- predsort(compare_objects_by(id), [object(o1,[id=2]),object(o0,[id=1])] , Ks).
object_id_value(Id,object(_,L),Val) :-
member((Id=Val), L).
compare_objects_by(Id,<, X, Y) :-
object_id_value(Id, X, N),
object_id_value(Id, Y, M),
sort([N,M], [N|_]).
compare_objects_by(Id,>, X, Y) :-
object_id_value(Id,X, N),
object_id_value(Id,Y, M),
sort([N,M], [M|_]).
compare_objects_by(_,=, _, _).
However, there is another point here. Is comparison really well
defined? Are there terms, that compare both > and < ? Or > and =? If
you look at the last fact...
?- compare_objects_by(qq1,=,qq2,qq3).
This means that all objects are equal - provided someone asks that
question!
Further, consider when ?- compare_objects_by(Id,<,X,Y). may fail. It
does not only fail, if X >= Y, it also fails if one of the first two
goals in the corresponding rule fails. E.g., if a term is not an
object, or if the key is not provided.
?- predsort(compare_objects_by(weight), [ noobject,object(obj21, [weight=200])],Xs).
Xs = [noobject].
_______________________________________________
SWI-Prolog mailing list
SWI-Prolog@...
https://mailbox.iai.uni-bonn.de/mailman/listinfo.cgi/swi-prolog