Sort using a custom comparator: Difference between revisions

Content added Content deleted
(→‎{{header|Pascal}}: added example)
m (→‎{{header|AppleScript}}: →‎Vanilla: New sort handler URL, tidy-up.)
Line 879: Line 879:


===Vanilla===
===Vanilla===

While vanilla AppleScript doesn't have sort facilities of its own, a customisable sort written in vanilla, such as [https://macscripter.net/viewtopic.php?pid=194430#p194430 this one on MacScripter], can be fed user-defined comparison handlers to do practically any kind of sorting. The following assumes that the customisable sort just mentioned has been compiled and saved in a suitable "Script Libraries" folder as "Custom Iterative Ternary Merge Sort.scpt":

<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
use sorter : script "Custom Iterative Ternary Merge Sort"
use sorter : script ¬
"Custom Iterative Ternary Merge Sort" --<www.macscripter.net/t/timsort-and-nigsort/71383/3>

set listOfText to words of "now is the time for all good men to come to the aid of the party"


-- Sort customiser.
script descendingByLengthThenAscendingLexicographically
script descendingByLengthThenAscendingLexicographically
on isGreater(a, b)
on isGreater(a, b)
set lenA to (count a)
set lenA to a's length
set lenB to (count b)
set lenB to b's length
if (lenA = lenB) then
if (lenA = lenB) then return (a > b)
return (a > b)
return (lenB > lenA)
else
return (lenB > lenA)
end if
end isGreater
end isGreater
end script
end script


set listOfText to words of "now is the time for all good men to come to the aid of the party"
-- Sort the whole list using the above customiser.
tell sorter to ¬
tell sorter to sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
return listOfText</syntaxhighlight>
return listOfText</syntaxhighlight>