[alexandria-devel] char-digit
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.
2009/7/15 Gustavo <gugamilare@gmail.com>:
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.
The strangely named CL:DIGIT-CHAR-P does this -- and will get numeric Unicode characters right as well in Unicode enabled implementations. Chees, -- Nikodemus
On Jul 15, 2009, at 00:52 , Gustavo wrote:
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.
See also DIGIT-CHAR-P: "Tests whether char is a digit in the specified radix (i.e., with a weight less than radix). If it is a digit in that radix, its weight is returned as an integer; otherwise nil is returned." <http://www.lispworks.com/documentation/lw50/CLHS/Body/f_digi_1.htm>
participants (3)
-
Gustavo
-
Michael Weber
-
Nikodemus Siivola