planet scheme上23号的Programming Praxis: 26进制的算术计算。大意是:a表示0,b表示1,...,z表示25,构成一个26进制的数字。在这个体系下进行乘法运算。我的实现如下:
- (define-module (base-26))
- ;; convert between a single char and a number
- ;; a -> 0, b -> 1, ..., z -> 25
- (define (char->number char)
- (- (char->integer char)
- (char->integer #\a)))
- (define (number->char num)
- (integer->char (+ num
- (char->integer #\a))))
- ;; convert between char-number and a normal number
- (export cnumber->number)
- (define (cnumber->number cnumber)
- (define len (string-length cnumber))
- (define minus (and (> len 0)
- (eqv? (string-ref cnumber 0) #\-)))
- (let loop ((result 0) (i (if minus 1 0)))
- (if (= i len)
- (if minus (- result) result)
- (loop (+ (* result 26)
- (char->number (string-ref cnumber i)))
- (+ i 1)))))
- (export number->cnumber)
- (define (number->cnumber num)
- (define minus (< num 0))
- (let loop ((result '()) (num (abs num)))
- (if (zero? num)
- (let ((full-result (map number->char
- (if (null? result)
- '(0)
- result))))
- (list->string (if minus
- (cons #\- full-result)
- full-result)))
- (loop (cons (remainder num 26) result)
- (quotient num 26)))))
- ;; operators
- (define (translator operator)
- (lambda args
- (number->cnumber
- (apply operator (map cnumber->number args)))))
- (export cadd)
- (define cadd (translator +))
- (export csub)
- (define csub (translator -))
- (export cmul)
- (define cmul (translator *))
- (export cdiv)
- (define cdiv (translator /))
阅读(4909) | 评论(0) | 转发(0) |