Search code examples
prologalphabetized

How to alphabetize a list in Prolog?


I want to alphabetize a list in prolog so I can then strip the head or tail of that list to deal with -- essentially make it easier to deal with things in alphabetical (or reverse alphabetical) order. I receive the words in varying order every time (not already alphabetized nor in the same order); eg,

'ra1' 'ra2' 'rb2' 'ra3' 'rb1'

I can't hard code the list; it might be 9, or 16 items, etc., so I want to sort them into a single alphabetized list of 'ra1', 'ra2', 'ra3', 'rb1', 'rb2'...

I should be able to use 'compare'. E.g.,

compare(Res, 'ra2', 'ra1').
Res = (>).

This is it for exactly 2 items, and now I need it for some unspecified number of items. Ideas?

places(['zzz', 'aaa']).

alph(Outlist, Inlist) :- 
    member(A, Inlist),
    member(B, Inlist),
    compare(<, A, B),
    A \= B,
    % and they go in that order in a new list.
    append([A], [B], Outlist).

Solution

  • Using standard sort/2 predicate is easy:

    ?- sort(['ra1', 'ra2', 'rb2', 'ra3', 'rb1'], Sorted).
    Sorted = [ra1, ra2, ra3, rb1, rb2].
    

    If your list can have duplicates, change sort to msort, because sort/2 eliminates duplicates.