-
Notifications
You must be signed in to change notification settings - Fork 132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A sort that doesn't remove duplicates could be useful #1163
Comments
I think :- use_module(library(pairs)). samsort(Ls0, Ls) :- pairs_keys(Pairs0, Ls0), keysort(Pairs0, Pairs), pairs_keys(Pairs, Ls). Examples: ?- samsort("bbbbccccaa", Ls). Ls = "aabbbbcccc" ; false. ?- samsort([X,Y,X,Z,Y], Ls). Ls = [X,X,Y,Y,Z] ; false.
The nondeterminism occurs because we do not yet have JIT indexing (#192) which could help to distinguish the clauses of :- use_module(library(pairs)). :- use_module(library(lists)). samsort(Ls0, Ls) :- same_length(Ls0, Pairs0), pairs_keys(Pairs0, Ls0), keysort(Pairs0, Pairs), pairs_keys(Pairs, Ls). Yielding: ?- samsort("bbbbccccaa", Ls). Ls = "aabbbbcccc". ?- samsort([X,Y,X,Z,Y], Ls). Ls = [X,X,Y,Y,Z]. |
Several Prolog systems provide msort([], []) :- !.
msort([X], [X]) :- !.
msort([X, Y| Xs], Ys) :-
split([X, Y| Xs], X1s, X2s),
msort(X1s, Y1s),
msort(X2s, Y2s),
merge(Y1s, Y2s, Ys).
merge([X| Xs], [Y| Ys], [X| Zs]) :-
X @=< Y, !,
merge(Xs, [Y| Ys], Zs).
merge([X| Xs], [Y| Ys], [Y| Zs]) :-
X @> Y, !,
merge([X | Xs], Ys, Zs).
merge([], Xs, Xs) :- !.
merge(Xs, [], Xs). Fell free to reuse/improve on it. For tests, see https://github.com/LogtalkDotOrg/logtalk3/tree/master/tests/prolog/predicates/msort_2 |
This is from Quintus which was merged into SICStus 4. Prior to that SICStus did not have it. |
For whatever it's worth, I'd like to mention that I find it very surprising that the default of We're of course stuck with it since it is part of the ISO, but a built-in alternative that doesn't remove duplicates would be very welcome. |
|
Thank you for providing some context. And apologies for my phrasing in my previous comment. The only thing I wanted to convey was that a builtin |
An equivalent predicate to
sort/2
that doesn't remove duplicates.In SICStus Prolog, it seems that
samsort/2
does the trick: https://sicstus.sics.se/sicstus/docs/4.1.0/html/sicstus/lib_002dsamsort.html#lib_002dsamsortIn SWI-Prolog,
msort/2
andsort/4
are different options to get this behavior.The text was updated successfully, but these errors were encountered: