[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/GPar0q3v    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Sep 21:
; alien numbers

(define (digits n . args)
  (let ((b (if (null? args) 10 (car args))))
    (let loop ((n n) (d '()))
      (if (zero? n) d
          (loop (quotient n b)
                (cons (modulo n b) d))))))

(define (undigits ds . args)
  (let ((b (if (null? args) 10 (car args))))
    (let loop ((ds ds) (n 0))
      (if (null? ds) n
          (loop (cdr ds) (+ (* n b) (car ds)))))))

(define (char->digit lang)
  (lambda (c)
    (let loop ((lang lang) (d 0))
      (if (char=? (car lang) c) d
        (loop (cdr lang) (+ d 1))))))

(define (alien->number lang str)
  (let* ((lang (string->list lang))
         (radix (length lang))
         (str (string->list str)))
    (undigits (map (char->digit lang) str) radix)))

(define (digit->char lang)
  (lambda (d)
    (list-ref lang d)))

(define (number->alien lang n)
  (let* ((lang (string->list lang))
         (radix (length lang))
         (num (digits n radix)))
    (list->string (map (digit->char lang) num))))

(define (translate alien source target)
  (number->alien target (alien->number source alien)))

(display (translate "9" "0123456789" "oF8")) ; (9*10^0 = 9)
(newline)
(display (translate "Foo" "oF8" "0123456789")) ; (1*3^2 + 0*3^1 + 0*3^0 = 9)
(newline)
(display (translate "13" "0123456789abcdef" "01")) ; (1*16^1 + 3*16^0 = 19)
(newline)
(display (translate "CODE" "O!CDE?" "A?JM!.")) ; (2*6^3 + 0*6^2 + 3*6^1 + 4*6^0 = 454)
(newline)

(define (read-word)
  (let loop ((c (read-char)) (cs '()))
    (cond ((eof-object? c)
            (if (null? cs) c
              (list->string (reverse cs))))
          ((not (char-whitespace? c))
            (loop (read-char) (cons c cs)))
          ((pair? cs) (list->string (reverse cs)))
          (else (loop (read-char) cs)))))

(define (do-file filename)
  (with-input-from-file filename
    (lambda ()
      (let ((n (string->number (read-word))))
        (do ((i 1 (+ i 1))) ((< n i))
          (let ((alien (read-word))
                (source (read-word))
                (target (read-word)))
            (display "Case #")
            (display i)
            (display ": ")
            (display (translate alien source target)))
            (newline))))))


Output:
1
2
3
4
Foo
9
10011
JAM!


Create a new paste based on this one


Comments: