Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Inspired by Wil Doane, this is a probably broken function that's designed to take a list of 0s and 1s (say, from a matrix of indicator values like "single", "employed", "ownsHome") and generate a unique integer to represent that binary string
​(define (logicalToBinary listOfZeroesAndOnes powerOfTwo runningSum)
(if (= (cdr listOfZeroesAndOnes) `()); Not sure if this is right, but it should be "if you've exhausted the list,
; implemented as "if the remainder of the list equals an empty list"
(else return (logicalToBinary (cdr listOfZeroesAndOnes)
(+ powerOfTwo 1)
(+ runningSum (* runningSum powerOfTwo)))))
Copy link

briandk commented Dec 9, 2014

I might have made some errors in the incrementation process too, but I think you see what I'm getting at. Recurse the function by:

  • moving to the next list element (cdr listOfZeroesAndOnes)
  • upping the power of two (+ powerOfTwo 1)
  • multiplying the power of two by the corresponding element in the list (which, because it's a one or zero effectively turns on or off that "bit") (* runningSum powerOfTwo)
  • Accumulating the new "bit" into the number by summing it (+ runningSum [result of previous computation])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment