CS 201: Introduction to Racket

Define a list comprising 10 digits

In [1]:
(define digits '(0 1 2 3 4 5 6 7 8 9))

Define a function, num-to-word, which takes a single digit and returns the corresponding English word

In [2]:
(define (num-to-word num)                                                         
  (if (> num 9) #f                                                                
      (let ((numbers '("zero" "one" "two" "three" "four" "five" "six" "seven" "ei\
ght" "nine")))                                                                    
        (list-ref numbers num))))

Define a function, word-to-num, which is the inverse of num-to-word. Note that we define a sub-function within the function itself. The sub-function, find-index, is recursive.

In [18]:
(define (word-to-num word)                                                        
  (let ((numbers '("zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine")))                                                                        
    (define (find-index lst n)                                                    
      (cond ((null? lst) #f)                                                      
            ((equal? (car lst) word) n)                                         
            (else                                                                 
             (find-index (cdr lst) (+ n 1)))))                                   
    (find-index numbers 0)))

Test out the functions. map is a function that applies a function to elements of a list, returning a new list comprising the results from each function application. The term map comes from math, not geography.

In [19]:
(define x (map num-to-word digits))
In [20]:
x
Out[20]:
'("zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine")

x now contains a list of the words for the digits. We will now put the words in alphabetical order using sort and the comparison predicate string<? which returns true if the first string argument is alphabetically prior to the second string argument.

In [21]:
(define y (sort x string<?))

y now contains a list of the digits in alphabetical order.

In [22]:
y
Out[22]:
'("eight" "five" "four" "nine" "one" "seven" "six" "three" "two" "zero")

We next convert the words in y back to numerals using our word-to-num function and our new friend map.

In [23]:
(define z (map word-to-num y))
In [24]:
z
Out[24]:
'(8 5 4 9 1 7 6 3 2 0)

This list should look familiar.