Increment / Decrement a word value

Author: Ashley Truter
Return to REBOL Cookbook

Do you find yourself using code like the following to increment or decrement a number by one?

    record-position: record-position + 1
    record-position: record-position - 1

If so, then the following two functions may be of use to you:

    ++: func ['val [word!]] [set val 1 + get val]
    --: func ['val [word!]] [set val -1 + get val]

They are used as follows:

    ++ record-position
    -- record-position

Both functions work by taking a word and setting its value.

Why it's different...

Compare the above functions to the following function:

    inc: func [val] [val: val + 1]

which takes a copy of a value, increments it, and returns the value. It has no affect on the word itself that was used for the argument.

This difference is apparent when you run the following console session:

    >> pos: 1
    == 1
    >> inc pos
    == 2
    >> inc pos
    == 2
    >> ++ pos
    == 2
    >> ++ pos
    == 3

The INC function added one to a copy of the value of pos, while the ++ function added one to the word's value itself.

2006 REBOL Technologies REBOL.com REBOL.net