Unary - Binary message
Torge Husfeldt
jean-jacques.gelee at gmx.de
Thu Oct 25 08:20:43 UTC 2001
Hi Richard,
Your example will balk over the sequence:
c:= Counter new.
c decrementIfPositive.
Better write
decrementIfPositive
self value > 0 ifTrue:[value := value - 1].
Regards,
Torge
"Richard A. O'Keefe" wrote:
>
> "Gary McGovern" <garywork at lineone.net> wrote:
> [Alan Key wrote:
> A way around this is to make a class to hold numbers that can be
> incremented (we used to call this a "gauge"). If you stick one
> of these in a variable slot, then all will work pretty well.
> Can you see where you should subclass gauge?
> ]
> My guess would be make an IntegerArray with the index changing on
> incrementing. Close ?
>
> Perhaps a simpler example is a Counter.
>
> Create a new subclass Counter of Object with one instance variable 'value'.
> Give it the methods
>
> value "access method"
> value ifNil: [value := 0] "lazy initialisation to 0".
> ^value
>
> increment "bump value, return self"
> value := self value + 1
>
> decrementIfPositive
> value > 0 ifTrue: [value := self value - 1]
>
> isZero
> ^self value = 0
>
> Now you can do
> |c|
> c := Counter new.
> c value "==> 0"
> c isZero "==> true"
> c increment.
> c isZero "==> false"
> c decrementIfPositive.
> c decrementIfPositive.
> c value "==> 0"
>
> You don't want a counter that clamps at 0? Then roll your own.
> (Note that ++ in C++ and C99 will clamp for one type but not others.)
> You want a method to set a counter to any number? Add one.
More information about the Squeak-dev
mailing list
|