Sorting a list
The withoutLeadingArticle function
This custom function is called with a statement such as the following:
sort lines of field "Titles" by withoutLeadingArticle(each)
The custom function works in tandem with the
sort container command. When you sort the lines of a container, the
each keyword serves as a placeholder for each line in the container. In the above statement, each line is passed to the withoutLeadingArticle function, and the returned value is used as the sort key for that line. The withoutLeadingArticle function simply removes any leading articles (the words "A", "An", and "The"), leaving the rest of the title to be used as the sort key.
Using a custom function with the
each keyword makes the sort container command much more flexible, because you can use the custom function to create any custom sort criteria you want to use. You can eliminate certain parts of the lines being sorted from consideration, as we've done here. Or you can use another custom function to transform lines in other ways.
For example, you could write a custom function for international sorting, which would change accented characters like é or ü into their ASCII equivalents (e and u). A sort done with this custom function would sort accented characters as though they were the unaccented equivalents, instead of sorting all accented characters after the end of the unaccented alphabet.
The withoutLeadingArticle function code
function withoutLeadingArticle pText get word 1 of pText if it is "The" or it is "An" or it is "A" then ## we don't want to use it for the sort delete word 1 of pText end if return pText end withoutLeadingArticle
Many other such special-purpose sorting functions can be written. Here's another example, which transforms a wordy movie rating into a letter so the movies can be easily sorted by rating, from best to worst:
function letterGrade pRating switch pRating case "See early, see often!" return "A" break case "Worth the ticket price" return "B" break case "Wait for the video release" return "C" break case "Skip it." return "D" break case "Flee! Flee for your lives!" return "E" break end switch end letterGrade
If a list of movies has the movie rating as the last item of each line, you can sort the movies by their ratings using this statement:
sort lines of tMovies by letterGrade(last item of each)
Add your comment