[alexandria-devel] char-digit
Gustavo
gugamilare at gmail.com
Tue Jul 14 22:52:23 UTC 2009
I find very strange that the ANSI specification defines the function
DIGIT-CHAR, but doesn't also define CHAR-DIGIT. It would be nice to have it
in alexandria.
One can use char-code to implement it, but only assuming that the char-code
of alphabetic characters are sequential (which happens very oftenly, I don't
know any implementation in which this may not work, but this behaviour is
not required by the specification).
So, here is my suggestion:
(defun char-digit (char &optional (radix 10))
"Takes a character and returns its weight.
Signals an error if char is not a digit character in the given radix."
(assert (digit-char-p char radix) (char) "Character ~a is not a digit
character." char)
(let ((char (char-upcase char)))
#+(or sbcl clisp ecl cmucl openmcl
allegro lispworks corman gcl abcl unicode)
(cond
((char<= #\0 char #\9)
(- (char-code char) (char-code #\0)))
((char<= #\A char #\Z)
(+ 10 (- (char-code char) (char-code #\A))))
(t nil))
#-(or sbcl clisp ecl cmucl openmcl
allegro lispworks corman gcl abcl unicode)
(parse-integer (string char) :radix radix)))
I tested and it works. Well, I am open to suggestions, and feel free to
include this code in alexandria as well.
Gustavo.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/alexandria-devel/attachments/20090714/bfee24ca/attachment.html>
More information about the alexandria-devel
mailing list