Created
August 26, 2014 16:39
-
-
Save saolsen/699bff0085ba4a6ac5b4 to your computer and use it in GitHub Desktop.
number to binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(define (get-spaces-inner n spaces) | |
(define current-space (car spaces)) | |
(if (> current-space n) | |
(cdr spaces) | |
(get-spaces-inner n (cons (* current-space 2) spaces)))) | |
(define (get-spaces n) | |
(get-spaces-inner n '(1))) | |
(define (to-binary x spaces) | |
(define binary-digits | |
(first | |
(foldl (lambda (place val) | |
(define digits (first val)) | |
(define n (second val)) | |
(if (>= n place) | |
(list (cons 1 digits) (- n place)) | |
(list (cons 0 digits) n))) | |
(list '() x) | |
spaces))) | |
(reverse binary-digits)) | |
(define (number-to-binary n) | |
(define spaces (get-spaces n)) | |
(to-binary n spaces)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment