Skip to content

Instantly share code, notes, and snippets.

@kwrooijen
Last active May 22, 2020 11:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwrooijen/7bad800cc86a2f020e07 to your computer and use it in GitHub Desktop.
Save kwrooijen/7bad800cc86a2f020e07 to your computer and use it in GitHub Desktop.
Decimal to Binary conversion options in Scheme
;; Very clean, but is not tail recursive!
(define (dec->bin n)
(cond ((zero? n) '())
(else (cons (remainder n 2)
(dec->bin (quotient n 2))))))
;; Not so clean, but is tail recursive.
(define (dec->bin n)
(letrec ((recc (lambda (acc n)
(cond ((zero? n) acc)
(else (recc (cons (remainder n 2) acc)
(quotient n 2)))))))
(recc '() n)))
;; Not much worse than the cleanest one, but uses optional args.
(define* (dec->bin n #:optional (acc '()))
(cond ((zero? n) acc)
(else (dec->bin (quotient n 2)
(cons (remainder n 2) acc)))))
(dec->bin 9) ;; => '(1 0 0 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment