Re: [eclipse-users] Question about setof/3

From: Andrew Eremin <ae_at_...2...>
Date: Fri, 27 Oct 2006 11:49:13 +0100
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi Ulrich,

>>> a question about setof/3: The manual states that the result is sorted
>>> but I could not find according to which ordering.  I guess, it's the
>>> standart term order.
> 
>>> How could an implementation of setof/3 look like that uses an arbitrary,
>>> i.e., user-supplied ordering?
> 
>> Use bagof/3 (or the faster findall/3), and sort the resulting list
>> afterwards.
> 
> I need to sort the result of bagof/3 according to a user-supplied function.
> I thought of something like the Java function "sort(List,Comparator)" in
> java.util.Collections, e.g., a predicate sort/3 with 
> sort(+Comparator,+Random,-Sorted).  I did not find anything similar in the
> Referendce Manual.
> 
> Can you suggest me some code that I could reuse?

Joachim's suggestion would still be the best option if the user can be
required to supply a predicate that maps a list element to an "order
value" instead of a comparator. If that's not possible, then here's a
simple implementation using insertion sort. I'm assuming there's an
appropriate specification of Goal to find a list element and that
Compare is the functor of the user-supplied arity 2 comparison predicate
that succeeds if its first argument precedes its second argument in the
desired ordering and fails otherwise:

...
findall(Term, Goal, List),
(
    foreach(Term, List),
    fromto([], In, Out, Sorted),
    param(Compare)
do
    user_insertion_sort(In, Term, Compare, Out)
),
...

user_insertion_sort([], Term, _Compare, [Term]).
user_insertion_sort([H|T], Term, Compare, Sorted) :-
    Comparison =.. [Compare, H, Term],
    ( call(Comparison) ->
        Sorted = [H|Sorted0],
        user_insertion_sort(T, Term, Compare, Sorted)
    ;
        Sorted = [Term, H|T]
    ).

Versions using other sorting algorithms (merge sort, bubble sort etc.)
are an exercise for the reader ;)

	Andy
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFFQeQpdLb1MBw2wdgRApRMAJ9Qh7O3XNsJ0ZnMhk7MU2CbEU2h7ACg0muW
+Mi2RPNzGlS+mHdY0vuIrrs=
=og5/
-----END PGP SIGNATURE-----
Received on Fri Oct 27 2006 - 11:46:38 CEST

This archive was generated by hypermail 2.3.0 : Wed Sep 25 2024 - 15:13:20 CEST