[plt-scheme] boolean operators on integers

From: Richard Cleis (rcleis at mac.com)
Date: Sat Jul 12 22:33:38 EDT 2008

On Jul 12, 2008, at 7:44 PM, Henk Boom wrote:

> 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:

This *is* a fun way.  In the pressure packed moments of programming, I  
would not have been able to make this work as fast as my hack or Eli's  
solution.  I often wonder how fast I would be if I were a 'real'  
Scheme programmer.
> (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.

The ordering is not a problem.  When working with hardware problems  
that these functions would solve, the number of bits are normally  
fixed and small.  The important issue is to have the hardware-specific  
complication in one place.  The arguments of the function that is  
applied to the list essentially document the arrangement of the bits.



>    Henk
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.