Rhyming Sort
December 8, 2020
Here is our solution:
(define (reverse-word str) (list->string (reverse (string->list str)))) (define (rhyming-lt? a b) (string<? (reverse-word a) (reverse-word b))) (define (rhyming-sort words) (sort rhyming-lt? words))
And that’s it, three one-liners that are nearly as simple as the Unix pipeline:
> (rhyming-sort '("falsely" "fly" "freely" "sorely" "surely")) ("freely" "sorely" "surely" "falsely" "fly")
You can run the program at https://ideone.com/4dNypS.
Here is a “one-liner” using standard R7RS Scheme and a couple of well
known helpers that seems very close in spirit to the Unix pipeline
solution. In comparing it to the solution by @programmingpraxis, one
difference is that this one makes only Theta(n) string-reversals
instead of Theta(n log n). Based on some very quick tests on larger
inputs (e.g., /usr/share/dict/words on Debian GNU/Linux), the
difference can be quite significant (10x).
Output:
We might as well use some actual poetry for our test data, so here is some Chaucer. After sanitizing the text, reverse all words, sort with appropriate collation (to get, for example, ‘vertú’ in the right place – Unicode combining characters might be a problem), and reverse again before final output:
Klong
Adopting Chaucer’s sample text (Thanks, @matthew), I get the following:
A common lisp solution.