Skip to content

Instantly share code, notes, and snippets.

@briandk
Created December 9, 2014 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandk/4cad2dfd32e783e2055c to your computer and use it in GitHub Desktop.
Save briandk/4cad2dfd32e783e2055c to your computer and use it in GitHub Desktop.
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"
; http://stackoverflow.com/questions/9115703/null-value-in-mit-scheme
runningSum)
(else return (logicalToBinary (cdr listOfZeroesAndOnes)
(+ powerOfTwo 1)
(+ runningSum (* runningSum powerOfTwo)))))
@briandk
Copy link
Author

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