[plt-scheme] boolean operators on integers

From: Henk Boom (lunarc.lists at gmail.com)
Date: Sat Jul 12 21:44:57 EDT 2008

2008/7/12 Matthias Felleisen <matthias at ccs.neu.edu>:
>
> On Jul 12, 2008, at 12:13 PM, Richard Cleis wrote:
>
>> This is boring practical stuff, though; it's not as fun as using
>> exponentiation for implementing logical negation. :)
>
>
> I don't think the design of such a function is boring:
>
>  ;; bits->list : Bits -> [Listof Boolean]
>
> would clearly do just the right thing.

It wasn't boring for me either =), here's what I had fun coming up with:

(define (bcar bits)
  (bitwise-and 1 bits))
(define (bcdr bits)
  (arithmetic-shift bits -1))
(define (bcons bit bits)
  (bitwise-ior bit (arithmetic-shift bits 1)))
(define (bnull? bits)
  (= bits 0))
(define bnull 0)

(define (bfoldl proc init bits)
  (if (bnull? bits) init
    (bfoldl proc
            (proc (bcar bits) init)
            (bcdr bits))))

(define (bits->list bits)
  (bfoldl (lambda (bit bools) (cons (= bit 1) bools)) '() bits))

(define (list->bits bools)
  (foldl (lambda (bool bits) (bcons (if bool 1 0) bits)) 0 bools))

I like the symmetry between bits->list and list->bits.

This puts low-order bits at the end of the list, which has the problem
that you have to prepend a number of falses before passing the list to
handle-fridge-status. With the low-order-bits at the beginning of the
list, you could make handle-fridge-status's arguments default to false
to make the apply work.

    Henk


Posted on the users mailing list.