4

Common Lisp provides the lovely ~r directive for printing cardinal English numbers. For example:

(format nil "~r" 27) -> "twenty-seven"

Does lisp provide a directive (or some library function) that does the reverse, from cardinal English numbers to integer values? I'm using Allegro CL on a Windows machine.

EDIT: I'm looking for this type of functionality in a cleaner fashion:

(defconstant +cardinal-number-map+
    (loop for number from 0 to 100
        collect (cons (format nil "~r" number) number)))

(defun cardinal->int (cardinal)
  (cdr (assoc cardinal +cardinal-number-map+ :test #'string-equal)))
ElliotPenson
  • 354
  • 1
  • 10
  • In general, it's hard to invert **format** results, as discussed in [http://stackoverflow.com/q/23489859/1281433](Is there an inverse of Common Lisp's FORMAT?). This case would be a bit easier, but since the output of `~r` isn't precisely defined, an approach like yours is probably the most portable. – Joshua Taylor Jan 19 '15 at 19:26

1 Answers1

2

Does lisp provide a directive (or some library function) that does the reverse, from cardinal English numbers to integer values?

The short answer is "no". You can read in different radices, but not the English text. That said, doing this type of reading is a common enough exercise that you can find code out there that will do it. For instance, on the Code Golf site, there's a question, Convert English to a number. I don't see any Lisp solutions there, but there are some short answers that could be translated without too much trouble. (The Javascript answer is short and might be a nice candidate.)

However, because format's output isn't specified precisely, there's not going to be a simple and portable solution that will work with every implementation's format output. For that, you might have to do something like what you suggested in the question.

Community
  • 1
  • 1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353