Seemingly Odd Behavior for Arithmetic Operations


#1

I’ve come across what seems to be odd behaviour in some of my mathematical expressions. I’m not sure if it’s a bug or a feature because I know what it’s doing, it just seems really odd to me that it’s doing it.

As a quick test you can run this in the workbench.


-1-2-3             //result 0
-1-2+3            //result -6
[-1-2]-3           //result -6

-1-2-3-4          //result -4
[[-1-2]-3]-4      //result -10
[[-1-2]-3-4]      //result -2

etc.

Is that the expected behaviour? I would have thought :sk: would use normal (at least what i considered normal) on paper order of operations for arithmetic expressions but it seems like the sign is being carried forward as a multiplication to the successive term?

If this is expected behaviour, I’m curious about the reasoning.

Cheers and thanks!


#2

SkookumScript has no operator precedence order just like Smalltalk (which SkookumScript is originally based on).

Every expression is read left to right and every expression is greedy - meaning it tries to grab up as big an expression as possible.

// So this
-1-2-3
// Is read as
-1 - [-2 - [3]]

You can read more about it in Code blocks to specify order in the online docs.

We’ve talked about it quite a bit over the years and we decided a while ago that adding precedence is the way to go moving forward. We just haven’t had a chance to do it yet. We also have an idea for a mechanism to ensure that existing code that depends on there being no operator precedence order will still work and can be either kept or phased out gradually.


#3

AH ok yeah that makes WAY more sense now. I’d had a feeling I had maybe missed something in the docs somewhere but hadn’t had a chance to dig through looking yet. I just got so used to the way C and C likes do it I guess I forgot there are other ways :smiley:

Thanks for the explanation!


#4

That’s one of the reasons why we expect to add operator precedence - people will most likely be familiar with it from C++ and similar languages.

If you haven’t looked yet, the Primer in the online docs is the best source of learning for Sk. It has lots of similarities to other languages though it pulls from many different languages and it has its own unique features too.


#5

Funnily enough I had bookmarked the Primer eariler today and was planning on going through it over the weekend. One of my first year CS profs always tried to hammer RTFM into us, usually I remember, this time I didn’t. :rofl: