Last active
October 29, 2019 18:04
-
-
Save Yeboster/3a7cf4fe1b734272f16be425cda31e77 to your computer and use it in GitHub Desktop.
binary rational number to decimal representation - scheme
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
(define find-point | |
(lambda (str) | |
(let ((last-pos (- (string-length str) 1))) | |
(let ((point? (char=? #\. (string-ref str last-pos)))) | |
(cond ((= (string-length str) 1) (if point? last-pos -1)) | |
(point? last-pos) | |
(else (find-point (substring str 0 last-pos)))))))) | |
(define binary-sum | |
(lambda (str exp-num) | |
(let ((char-to-bin (lambda (char) (if (char=? char #\0) 0 1))) (digit-value (lambda (num) (* num (expt 2 exp-num))))) | |
(let ((fst-digit-value (digit-value (char-to-bin (string-ref str 0))))) | |
(if (= (string-length str) 1) | |
fst-digit-value | |
(+ (binary-sum (substring str 1) (- exp-num 1)) fst-digit-value)))))) | |
(define string-remove-at | |
(lambda (str pos) | |
(string-append (substring str 0 pos) (substring str (+ pos 1))))) | |
(define bin-rep->number-abs | |
(lambda (str) | |
(let ((point-pos (find-point str))) | |
(if (= -1 point-pos) | |
(binary-sum str (- (string-length str) 1)) | |
(binary-sum (string-remove-at str point-pos) (- point-pos 1)))))) | |
(define bin-rep->number | |
(lambda (str) | |
(let ((fst-char-is? (lambda (char) (char=? (string-ref str 0) char)))) | |
(cond ((fst-char-is? #\+) (bin-rep->number-abs (string-remove-at str 0))) | |
((fst-char-is? #\-) (* -1 (bin-rep->number-abs (string-remove-at str 0)))) | |
(else (bin-rep->number-abs str)))))) | |
(bin-rep->number "+1101") ; => 13 | |
(bin-rep->number "0") ; => 0 | |
(bin-rep->number "10110.011") ; => 22.375 | |
(bin-rep->number "-0.1101001") ; => -0.8203125 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment