Sorting In REXX Made Easy
MartinPacker 11000094DH Comments (2) Visits (14001)
In REXX sorting is a fraught exercise - and you tend to have to resort to other programs to do it:
but you might decide your sort is low volume enough to do in REXX. The trouble is it’s difficult to write a routine that isn’t specific on how the data is sorted, or rather how two items are compared - as we shall see.
Following on from Dragging REXX Into The 21st Century? here’s a technique that is quite general. It uses the REXX INTERPRET instruction.
The problem of sorting comprises two challenges:
This post is mostly about Challenge 1, though the code presented also addresses Challenge 2.
Comparing Two Items
It’s easy to do a straight numeric comparison in REXX, such as
but more complex comparisons are, ahem, more complex. But, more to the point, a generalised comparison is difficult to do, which is where INTERPRET comes in.
Sample Sort Code
In what follows the program works. That isn’t to say the sorting algorithm is the most efficient over all sets of data, but this post isn’t really about the sort’s efficiency.
The item comparison routine in this example is, of course, somewhat artificial - and not one I’m likely to use. It compares the length of the second token in each stem variable. I chose it as an example of something that’s not easy to do in, say, DFSORT. The real point is you can compare items using arbitrarily complex criteria. If your collection of stem variables was more complex than this - essentially a list of objects - you’d want the sophistication this approach allows.
Incidentally when it comes to INTERPRET performance I think it depends on which statements are actually interpreted and which have already been tokenised:
In the above example code you’ll notice I’m using a hard-coded set of stem variable names. In my actual production code I’ve generalised to allow any stem variable names - so I’m actually much heavier in my use of INTERPRET.
I’m leaning towards INTERPRET in more cases - provided it doesn’t obscure the meaning.
At the start of this post I mentioned DFSORT and Unix sort as alternatives. I think you should consider them, though their limitations and the need to work hard at “marshalling” to use them will limit their appeal. So, I hope you’ll find the technique presented in this post useful for the cases where they’re not appealing.
The most important piece of this post - and the main reason for writing it - is the notion of using a single sorting routine and handing it the name of an item comparison routine. This should lead to code that’s more maintainable. Its long been the staple of other programming languages. You can do it with REXX, too!