[Solved] how to spell a number in racket? (spellNum) [closed]


EDITED:

A complete solution has been posted, so I guess it’s ok for me to show you how to write an idiomatic procedure. Notice that number->list uses a technique called tail recursion for efficiently expressing a loop. Although (coming from a Python background) it might be tempting to use an explicit looping construct (as shown in @uselpa’s answer), to really get in the spirit of Scheme you should learn how to write a loop using recursion, it’s the standard way to express iteration in this language (When in Rome, do as the Romans do):

(define (digit->symbol n)
  (case n
    ((0) 'zero)
    ((1) 'one)
    ((2) 'two)
    ((3) 'three)
    ((4) 'four)
    ((5) 'five)
    ((6) 'six)
    ((7) 'seven)
    ((8) 'eight)
    ((9) 'nine)
    (else (error "unknown digit:" n))))

(define (number->list n)
  (let loop ((acc '()) (n n))
    (if (< n 10)
        (cons n acc)
        (loop (cons (remainder n 10) acc) (quotient n 10)))))

(define (spellNum n)
  (map digit->symbol (number->list n)))

The trick is to split the problem in different parts, digit->symbol converts a single digit into a symbol. Similarly, number->list transforms a number into a list of numbers. After writing those helper procedures it’s easy to write spellNum, which works as expected:

(spellNum 467)
=> '(four six seven)

6

solved how to spell a number in racket? (spellNum) [closed]