%Source: https://sites.google.com/site/prologsite/prolog-problems %query:lsort(g,f). % 1.28 (**) Sorting a list of lists according to length % % a) length sort % % lsort(InList,OutList) :- it is supposed that the elements of InList % are lists themselves. Then OutList is obtained from InList by sorting % its elements according to their length. lsort/2 sorts ascendingly, % lsort/3 allows for ascending or descending sorts. % (list_of_lists,list_of_lists), (+,?) lsort(InList,OutList) :- lsort(InList,OutList,asc). % sorting direction Dir is either asc or desc lsort(InList,OutList,Dir) :- add_key(InList,KList,Dir), keysort(KList,SKList), rem_key(SKList,OutList). add_key([],[],_). add_key([X|Xs],[L-p(X)|Ys],asc) :- !, length(X,L), add_key(Xs,Ys,asc). add_key([X|Xs],[L-p(X)|Ys],desc) :- length(X,L1), L is -L1, add_key(Xs,Ys,desc). rem_key([],[]). rem_key([_-p(X)|Xs],[X|Ys]) :- rem_key(Xs,Ys). length(_,_).