Define a list comprising 10 digits
(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
(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.
(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.
(define x (map num-to-word digits))
x
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.
(define y (sort x string<?))
y now contains a list of the digits in alphabetical order.
y
We next convert the words in y back to numerals using our word-to-num
function and our new friend map
.
(define z (map word-to-num y))
z
This list should look familiar.