Post Reply 
(49G/50g) Shortest code to increment a variable?
04-20-2023, 11:50 AM
Post: #1
(49G/50g) Shortest code to increment a variable?
I can think of trivial code like this to increment variable A by one:

A 1 + ‘A’ STO

Are there shorter, faster, more elegant ways to do this?
Thanks,
A
Find all posts by this user
Quote this message in a reply
04-20-2023, 12:21 PM
Post: #2
RE: (49G/50g) Shortest code to increment a variable?
(04-20-2023 11:50 AM)acser Wrote:  I can think of trivial code like this to increment variable A by one:

A 1 + ‘A’ STO

Are there shorter, faster, more elegant ways to do this?
Thanks,
A

1
'A'
STO+

(also available STO- STO* STO/)

or

'A'
INCR

(INCR and DECR increments and decrements by 1 and returns new value)

You can find all commands in menu PRG-->MEM-->ARITH
Find all posts by this user
Quote this message in a reply
04-20-2023, 12:38 PM
Post: #3
RE: (49G/50g) Shortest code to increment a variable?
Note that all three of these methods are significantly slower than keeping the value represented by A on the stack rather than in a variable. Even if the value is on a higher stack level, e.g. ROT 1. + UNROT is still faster than INCR or STO+. Also use real numbers rather than exact integers if possible.

These optimizations are not important if the incrementing only occurs a few times in the running of the program but they should be considered if the incrementing occurs inside a loop, which it usually does.
Find all posts by this user
Quote this message in a reply
04-20-2023, 07:11 PM
Post: #4
RE: (49G/50g) Shortest code to increment a variable?
Thank you all. Very useful.
Find all posts by this user
Quote this message in a reply
04-20-2023, 08:45 PM
Post: #5
RE: (49G/50g) Shortest code to increment a variable?
Note also that STO+
can be used with a variable that contains a list.

Suppose you have done {1 2 3} 'A' STO.
Then try 20 'A' STO+
and press A
to see the new list A {20 1 2 3},
with the number added as the first element of the list A.

Try now with "test" 'A' STO+
and press A
to see the new list A {"test" 20 1 2 3}.

Instead of a string,
you could have a variable name such as 'B':
Try 'B' 'A' STO+
and press A
to see the new list A {B "test" 20 1 2 3}.
Find all posts by this user
Quote this message in a reply
Post Reply 




User(s) browsing this thread: 1 Guest(s)