HOME Try Sather Post Messages

9. Operators

1. Introduction

Sather's operators are syntax sugars of certain methods. These syntax sugars make Sather codes readable.

As the methods for operators are pre-defined, you can re-define the operators of your own classes.

2. Arithmetic operators

Table 1 shows arithmetic methods and corresponding operators.

Table 1: Arithmetic methods and corresponding operators.
Methods Operators
a.plus(b) a + b
a.minus(b) a - b
a.times(b) a * b
a.div(b) a / b
a.pow(b) a ^ b
a.mod(b) a % b
a.is_lt(b) a < b
a.is_eq(b) a = b
-a a.negate
~a a.not

Table 2 shows comparison operators with their corresponding methods.

Table 2: Comparison operators and their corresponding methods.
Operators Corresponding Methods
a <= b b.is_lt(a).not
a >= b a.is_lt(b).not
a /= b a.is_eq(b).not
a > b b.is_lt(a)

3.Accessing array elements

You can refer and assign array elements by using aget and aset methods, respectively. Table 3 shows the syntax sugars for these.

Table 3: Methods to access array elements with their syntax sugars.
Methods Syntax sugars
b := a.aget(i) b := a[i]
a.aset(i, b) a[i] := b

4. Defining your own operators

You can define your own operators by defining methods such as is_eq, plus, minus, aget, aset, and so on. For instance, the plus method of the STR class has been re-defined so that you can concatenate any objects that can be converted to strings.

The INT class has its aget and aset methods to access the array of bits. You can modify the program crypt.sa in Abstract Classes by using this methods. The integers in the program are XORed by bxor. It is unnecessary to get XOR's of whole 32 bits because the integers converted from CHAR's, have only 8 bits. Following is a more efficient code.

-- replace  fs := fs + s.elt!.int.bxor(key_rotate!).char; at line 64 by following code
	 fs := fs + cxor(s.elt!.int,key_rotate!);

-- add following method to class XOR 
   private cxor(m,n:INT):CHAR is
	 i:=CHAR::asize.times!;                -- 8.times!
	 k:=k.aset(i, m[i].xor(n[i]));
      return k.char;

5. Summary

Sather allows you to re-define the operators like other OO languages.
Intuitive definition of the operators makes your codes readable.

HOME Try Sather Post Messages