Useful function: ordinal numbers

Started by TedWalther, July 27, 2014, 01:40:41 AM

Previous topic - Next topic

TedWalther

Since format doesn't print numbers as ordinals, (fault of the underlying printf function) I made a function to do it.



This takes a number, and returns a string in ordinal form.



1 becomes 1st

2 becomes 2nd

3 becomes 3rd

4 becomes 4th



And so on.



(define (ordinal n)
  (let (nn (string n))
    (cond
      ((regex {1[123]$} nn) (string nn "th"))
      ((regex {1$} nn) (string nn "st"))
      ((regex {2$} nn) (string nn "nd"))
      ((regex {3$} nn) (string nn "rd"))
      ((regex {[4567890]$} nn) (string nn "th"))
      (true nn))))
(global 'ordinal)


I've put this in my init.lsp.  Handy little function.



Sample usage:



> (ordinal 3)
"3rd"
> (ordinal 4)
"4th"
> (ordinal 65)
"65th"
> (ordinal 10)
"10th"
> (ordinal 11)
"11th"
> (ordinal 12)
"12th"
> (ordinal 13)
"13th"
> (ordinal 14)
"14th"
> (ordinal 24)
"24th"
> (ordinal 23)
"23rd"
> (ordinal 21)
"21st"
Cavemen in bearskins invaded the ivory towers of Artificial Intelligence.  Nine months later, they left with a baby named newLISP.  The women of the ivory towers wept and wailed.  \"Abomination!\" they cried.