Variable Assignment
Assigning variables in Smallworld Magik can be accomplished with a simple construct known as the left chevron (<<). A simple variable assignment will look like this:
a << 7This expression states that the variable “a” becomes 10. More complicated expressions can also be expressed in this way.
b << 7 * a + 7or
c << (b-3).squaredVariables may be named almost anything you want, with the following constraints:
- Start with a-z, or !
- Contain a-z, 0-9, _, ?, !
- Unlimited length
- Case independent (sorry camelCase junkies)
Variables may also be assigned in serial or parallel. A series assignment might look like this:
a << b << c << 7This is the same as a << (b << (c << 1))
three << (two << (one << 1) +1) +1
Parallel variable assignment might look like this:
(a,b,c) << (1,2,3)(s,c) << theta.sincos() <--this works because sincos() returns two values, sin and cos
There is a somewhat classic programmer problem for swapping two variables without using a temp variable. One of the many solutions being as follows:
a << a+bb << a-b
a << a-b
Smallworld Magik has a more elegant solution however, using a swapping assignment.
(a,b) << (b,a)Variable can be assigned inside other structures as well. A common use for this is to assign a variable during an if-then evaluation.
_if (z<< (x.squared + y.squared).sqrt) <= minimum_distance_then
write(“The value “,z,” is too small!”)
_endif
There are other variations to the left chevron that have their uses.
a +<< 1 will increment a by 1.
a -<< 1 will de-increment a by 1.
a *<< 2 will multiply a by 2.
a /<< 2 will divide a by 2.
A seldom used, but kind of interesting one is known as the boot assignment.
a << b ^<< 10This is the same as saying a << b followed by b << 10. Essentially b becomes 10 and returns its original value which is in turn assigned to a.
One final note on Smallworld Magik variables is that developers tend to use longer names to describe most variables separated by an underscore (_) with the exception being when it is an iterated variable inside of a loop. The variable ‘e’ is used by many to indicate an element inside of a loop, while more permanent element references would be named an_element.