Search code examples
smalltalk

Understanding weird logical operators in smalltalk


So my problem is the following:

When char = 0

boolean = char ~= 0 & char ~= 256

evaluates to true and if I invert the statements like so:

boolean = char ~= 256 & char ~= 0

I get false.

What's happening?. I am expecting false on both cases.


Solution

  • As @Uko said, you must understand the precedence of messages: all binary messages (+ = < & ~= etc..) are evaluated from left to right.

    Thus you evaluate:

    (((boolean = char) ~= 256) & char) ~= 0
    

    I think you were after:

    boolean := (char ~= 256) & (char ~= 0).
    

    So what happens with your expression ?

    • booleanis presumably unitialized (thus nil)
    • char is 0.
    • boolean = char is false.
    • false ~= 256 is true.
    • true & char is char (see below why)
    • char ~= 0 is false (since char = 0)

    If you invert 0 and 256, only the last step changes and awnswer true.

    The interesting part is the implementation of message & in class True: it probably does not assert that the parameter is a Boolean and looks like:

    & aBoolean
        ^aBoolean
    

    If you pass something that is not a Boolean, (like 0 in your case), it will return this thing, whatever surprising it can be...

    If you use an IDE (Squeak/Pharo/Visualworks/Dolphin... but not gnu Smalltalk) I suggest you use the menu Debug It and evaluate the expression step by step in the Debugger.

    Last, note that char is probably not a good name in Smalltalk context: it might be misleading. Indeed, if it holds 0, it's rather an Integer, not a Character.