I was wondering if anyone could help me with this problem: I have to order a list using Prolog with Constraing Logic Programming and I must do it with the more efficient way I can.
So the main predicate I have defined is the next one:
order(Xs,Ys) :-
same_length(Xs,Ys), /* To determine the list Ys with the Xs' length */
perm(Xs,Ys), /* Permutation */
ordered(Ys), /* Is Ys ordered? */
! .
The implementation of each of the previous auxiliary predicates is as follows:
same_length(Xs,Ys) :-
length(Xs,L),
length(Ys,L).
perm([],[]).
perm([X|Xs],Ys) :- elem(X,Ys,Ws), perm(Xs,Ws).
ordered([]).
ordered([_]).
ordered([X,Y|Xs]) :- X =< Y, ordered([Y|Xs]).
elem(X,[X|Ys],Ys).
elem(X,[Y|Ws],[Y|Zs]) :- elem(X,Ws,Zs).
I have proved the program I made and it works! But I don’t know if it is possible to improve the efficiency, and if it is, how can I do it (I was reading this old thread here). Should I add or modify any of the constraints?
Thanks!
Your definition of
same_length/2will not terminate very often. Instead, considerequally, using
library(lambda)usein place of
It seems you want to reformulate sorting by stating first, that the list is ordered, and only then searching for a permutation. Below works in SICStus, SWI, YAP.
Please note that the arguments in perm/2 are now exchanged! Using SWI: