I have a list of attributes named FOO1, FOO2,...FOO100. How do I sort them so the numbers are in the right order?

Submitted by javelin on Sun, 2012-02-12 22:09

I have a list of attributes named FOO1, FOO2,...FOO100. How do I sort them so the numbers are in the right order?

The default PennMUSH sort() is lexicographic, which means that FOO2 will be sorted after FOO100.
For simple lists of numbers, you could do sort(1 2 ... 100,n) and get a numeric sort, but that won\'t work for attribute names with text before the numbers. Here\'s a few things that will:

&HELPER obj=[sub(after(%0,FOO),after(%1,FOO))]

sortby(obj/HELPER,FOO1 FOO2 ... FOO100)


&NUMSORT obj=[sort(%0,n)]

munge(obj/numsort, edit(FOO1 FOO2 ...,FOO,), FOO1 FOO2 ...)

The first version works by comparing the numbers after "FOO" in a given pair of attribute names, and returns a negative number when %0 should be before %1, a positive number when %1 should be before %0, and 0 when they\'re the same. This is exactly what sortby() needs to sort the list.
The second version uses edit() to build a list of just the numerical parts of the attributes, and munge sorts this list numerically and then returns the corresponding elements out of the original list.

2001-Mar-28 10:02am dunemush

Or, you could have named them as FOO001, FOO002, ..., FOO100 in the first place, thus allowing you to sort lexographically. You can generate zero-padded numbers this way:

> think iter(lnum(1, 100), rjust(##, 3, 0))

001 002 003 ... 100

2003-Apr-23 7:32am pmak