newLISP Fan Club

Forum => newLISP in the real world => Topic started by: TedWalther on July 27, 2014, 01:40:41 AM

Title: Useful function: ordinal numbers
Post by: TedWalther on July 27, 2014, 01:40:41 AM
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"