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))
      ((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)
> (ordinal 4)
> (ordinal 65)
> (ordinal 10)
> (ordinal 11)
> (ordinal 12)
> (ordinal 13)
> (ordinal 14)
> (ordinal 24)
> (ordinal 23)
> (ordinal 21)
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.
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 1 guest