Search code examples
schemeracketalphabet

Scheme - Converting Numbers to a Letter of Alphabet


I'd like to create procedures that would allow me to convert from a given number i to the i-th character in the alphabet.

For example:

(toChar 4) -> d
(toInt d) -> 4

The implementation of an alphabet here seems like it could work. This however, seems very inefficient as you would have to loop through the alphabet until you get to the number you are after.

Can this be done in a more concise way?


Solution

  • http://docs.racket-lang.org/guide/characters.html

    This part of the documentation explains it very clearly.

    So what you can do is the following:

    > (char->integer #\a)
    97
    > (char->integer #\b)
    98
    > (char->integer #\A)
    65
    

    Using this you can use a function as shown below:

    (define (to-letter n)
      (let ((charnum (+ n 96)))
        (integer->char charnum)))
    
    (define (to-int c)
      (let ((charnum (char->integer c)))
        (- charnum 96)))
    
    > (to-int (to-letter 1))
    1
    

    Be sure to check for bounds etc.

    Edit

    To be more in the spirit of the given SO question, you could store the characters in an array and then you have O(1) indexing.