Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #lang racket
  2.  
  3. (provide rebase from to)
  4.  
  5. (define (rebase list-digits in-base out-base)
  6. (to (from list-digits in-base) out-base))
  7.  
  8. (define (from list-digits in-base)
  9. (if (all? (list (> in-base 1)
  10. (all-good-numbers? list-digits in-base)))
  11. (my-from (reverse list-digits) in-base 0)
  12. #f))
  13.  
  14. (define (all? conditions)
  15. (if (null? conditions) #t
  16. (and (first conditions)
  17. (all? (rest conditions)))))
  18.  
  19. (define (all-good-numbers? digits base)
  20. (andmap (lambda (digit)
  21. (and (>= digit 0) (< digit base)))
  22. digits))
  23.  
  24. (define (my-from reversed-list-digits base n)
  25. (if (null? reversed-list-digits)
  26. 0
  27. (let* ([head (car reversed-list-digits)]
  28. [tail (cdr reversed-list-digits)]
  29. [res (* head (expt base n))])
  30. (+ res (my-from tail base (+ n 1))))))
  31.  
  32. (define (to num out-base)
  33. (if (all? (list (> out-base 1)
  34. (not (eq? num #f))))
  35. (if (eq? num 0)
  36. '( 0 )
  37. (reverse (my-to num out-base)))
  38. #f))
  39.  
  40. (define (my-to num base)
  41. (if (eq? num 0)
  42. '()
  43. (let-values ([(q r) (quotient/remainder num base)])
  44. (cons r (my-to q base)))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement