Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Integers to Characters in Common Lisp

Is there a way to parse integers to their char equivalents in Common Lisp?

I've been looking all morning, only finding char-int...

* (char-int #\A)

65

Some other sources also claim the existance of int-char

* (int-char 65)
; in: INT-CHAR 65
;     (INT-CHAR 65)
; 
; caught STYLE-WARNING:
;   undefined function: INT-CHAR
; 
; compilation unit finished
;   Undefined function:
;     INT-CHAR
;   caught 1 STYLE-WARNING condition

debugger invoked on a UNDEFINED-FUNCTION:
  The function COMMON-LISP-USER::INT-CHAR is undefined.

Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.

restarts (invokable by number or by possibly-abbreviated name):
  0: [ABORT] Exit debugger, returning to top level.

("undefined function")

What I'm really looking for, however, is a way of converting 1 to #\1

How exactly would I do that?

like image 712
Electric Coffee Avatar asked Oct 02 '14 08:10

Electric Coffee


2 Answers

To convert between characters and their numeric encodings, there are char-code and code-char:

* (char-code #\A)
65
* (code-char 65)
#\A

However, to convert a digit to the corresponding character, there is digit-char:

* (digit-char 1)
#\1
* (digit-char 13 16) ; radix 16
#\D
like image 139
jlahd Avatar answered Sep 18 '22 22:09

jlahd


There's already an accepted answer, but it can be just as helpful to learn how to find the answer as getting the specific answer. One way of finding the function you needed would have been to do an apropos search for "CHAR". E.g., in CLISP, you'd get:

> (apropos "CHAR" "CL")
...
CHAR-CODE                                  function
...
CODE-CHAR                                  function
...

Another useful resource is the HyperSpec. There's permuted index, and searching for "char" in the "C" page will be useful. Alternatively, in the HyperSpec, the chapter 13. Characters is relevant, and 13.2 The Characters Dictionary would be useful.

Both of these approaches would also find the digit-char function mentioned in the other answer, too.

like image 24
Joshua Taylor Avatar answered Sep 17 '22 22:09

Joshua Taylor