Useful function: ordinal numbers

Q&A's, tips, howto's

Useful function: ordinal numbers

Postby TedWalther » Sun Jul 27, 2014 8:40 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.

Code: Select all
(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:

Code: Select all
> (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.
TedWalther
 
Posts: 605
Joined: Mon Feb 05, 2007 1:04 am
Location: Abbotsford, BC

Return to newLISP in the real world

Who is online

Users browsing this forum: No registered users and 2 guests