Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #lang racket
- (provide rebase from to)
- (define (rebase list-digits in-base out-base)
- (to (from list-digits in-base) out-base))
- (define (from list-digits in-base)
- (if (all? (list (> in-base 1)
- (all-good-numbers? list-digits in-base)))
- (my-from (reverse list-digits) in-base 0)
- #f))
- (define (all? conditions)
- (if (null? conditions) #t
- (and (first conditions)
- (all? (rest conditions)))))
- (define (all-good-numbers? digits base)
- (andmap (lambda (digit)
- (and (>= digit 0) (< digit base)))
- digits))
- (define (my-from reversed-list-digits base n)
- (if (null? reversed-list-digits)
- 0
- (let* ([head (car reversed-list-digits)]
- [tail (cdr reversed-list-digits)]
- [res (* head (expt base n))])
- (+ res (my-from tail base (+ n 1))))))
- (define (to num out-base)
- (if (all? (list (> out-base 1)
- (not (eq? num #f))))
- (if (eq? num 0)
- '( 0 )
- (reverse (my-to num out-base)))
- #f))
- (define (my-to num base)
- (if (eq? num 0)
- '()
- (let-values ([(q r) (quotient/remainder num base)])
- (cons r (my-to q base)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement