(load "simply.scm")
; Example: Convert 39 to binary
;
; 39 / 2 = 19 R 1
; 19 / 2 =  9 R 1
;  9 / 2 =  4 R 1
;  4 / 2 =  2 R 0
;  2 / 2 =  1 R 0
;  1 / 2 =  0 R 1     BASE CASE
; Answer reads the remainders bottom to top: 100111

; What is needed:
; 1. A base case that returns ?
;    * Note that zero needs special handling
; 2. A recursive call that uses:
;    * Division
;    * Remainder
;    * Some combiner function to produce output with zeroes and ones

(define (toBinary decimalNum)
  (cond ((= decimalNum 0) 0)   ; zero ends up being a special case
        (else (helper decimalNum))))

(define (helper decimalNum)
  (cond ((= decimalNum 1) 1)
        (else (word (toBinary (floor (/ decimalNum 2)))
                    (remainder decimalNum 2)))))

; Converting a number to hexadecimal (base 16) is similar:

(define (hex-digit num)
  (cond ((= num 10) 'a)
        ((= num 11) 'b)
        ((= num 12) 'c)
        ((= num 13) 'd)
        ((= num 14) 'e)
        ((= num 15) 'f)
        (else num)))

(define (toHex num)
  (cond ((= num 0) '0x)
        (else (word (toHex (floor (/ num 16)))
                    (hex-digit (remainder num 16))))))