Enhancement Request: Adding population count for Integers to
the standard image
Matthew S. Hamrick
matthew.hamrick at gibson.com
Fri Dec 10 06:04:05 UTC 2004
Good recommendation. I've always been a fan of test-first
development... probably should have done this earlier. Attached is:
a. a change-set for Integer that includes a version of popCount that
throws an error if you invoke it on a negative number.
b. a SIUnit test subclass that does simple testing and has some
documentation
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Integer.msh.2.cs
Type: application/octet-stream
Size: 443 bytes
Desc: not available
Url : http://lists.squeakfoundation.org/pipermail/squeak-dev/attachments/20041210/6267940b/Integer.msh.2.obj
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PopCountTest.msh.1.cs
Type: application/octet-stream
Size: 3421 bytes
Desc: not available
Url : http://lists.squeakfoundation.org/pipermail/squeak-dev/attachments/20041210/6267940b/PopCountTest.msh.1.obj
-------------- next part --------------
On Dec 9, 2004, at 4:33 AM, st?phane ducasse wrote:
> Matthew
>
> it would be a really nice occasion to document your code with a couple
> of SUnit tests.
> http://www.iam.unibe.ch/~ducasse/Programmez/OnTheWeb/SUnitEnglish2.pdf
> It should take you 5 min and this way you will help the people looking
> at it.
>
> Stef
>
>
> On 9 d?c. 04, at 02:13, Richard A. O'Keefe wrote:
>
>> "Matthew Hamrick" <Matthew.Hamrick at gibson.com> wrote
>> (edited somewhat to take fewer lines and be more ASCII-friendly):
>>
>> popCount
>> "Answers the number of bits set in an integer."
>> | t1 t2 |
>> t1 := self.
>> t2 := 0.
>> [t1 == 0] whileFalse: [t1 := t1 bitAnd: t1 - 1. t2 := t2 + 1].
>> ^ t2
>>
>> What is this supposed to do when the number is negative?
>>
>> -1 bitAnd: -2 => -2
>> -2 bitAnd: -3 => -4
>> -4 bitAnd: -5 => -8
>>
>> In Squeak 3.6-5429-full.image, (-1 popCount) eventually terminates
>> because
>> m := -1 bitShift: 31.
>> m := m bitAnd: m - 1
>> sets m to 0, instead of to the correct value (-1 bitShift: 32).
>> First time I've ever had Squeak give me the wrong answer for an
>> integer calculation.
>>
>> Notionally, a Squeak negative integer has infinitely many 1 bits, so I
>> suggest
>>
>> popCount
>> "self >= 0 => answer the number of 1 bits in the binary
>> representation.
>> self < 0 => answer the number of 0 bits in the binary
>> representation.
>> Two's complement is assumed.
>> "
>> |m n|
>> (m := self) < 0 ifTrue: [m := -1 - self].
>> n := 0.
>> [m == 0] whileFalse: [m := m bitAnd: m-1. n := n+1].
>> ^n
>>
>> Another alternative would be to make it an error to send #popCount to
>> a
>> negative integer.
>>
>>
>
>
More information about the Squeak-dev
mailing list
|