Skip to content

Macro operators

Alex Zimin edited this page Jul 11, 2011 · 3 revisions

Table of Contents

Operators implemented as macros

Unary operators

Increment: ++

mutable i = 0;
i++;
assert(i == 1);

Decrement: --

mutable i = 0;
i--;
assert(i == -1);

Binary operators

Power: **

assert(3 ** 4 == 81);

Logical AND: &&

assert((true  && true)  == true);
assert((false && false) == false);
assert((false && true)  == false);
assert((true  && false) == false);

Logical OR: ||

assert((true  || true)  == true);
assert((false || false) == false);
assert((false || true)  == true);
assert((true  || false) == true);

Bitwise OR with check: %||

assert((0    %|| 0)    == false);
assert((0x01 %|| 0x10) == true);
assert((0x01 %|| 0x01) == true);
assert((0x10 %|| 0)    == true);

Bitwise AND with check: %&&

assert((0    %&& 0)    == false);
assert((0x01 %&& 0x10) == false);
assert((0x01 %&& 0x01) == true);
assert((0x10 %&& 0x11) == true);

Bitwise exclusive-OR (XOR) with check: %^^

assert((1 %^^ 0)    == true);
assert((0 %^^ 0)    == false);
assert((1 %^^ 1)    == false);
assert((0 %^^ 1)    == true);

The addition assignment: +=

mutable i = 1;
i += 2;
assert(i == 3);

The subtraction assignment: -=

mutable i = 3;
i -= 2;
assert(i == 1);

The binary multiplication assignment: *=

mutable i = 3;
i *= 2;
assert(i == 6);

The division assignment: /=

mutable i = 6;
i /= 2;
assert(i == 3);

The modulus assignment: %=

mutable i = 7;
i %= 2;
assert(i == 1);

The right-shift assignment: <<=

mutable i = 0x0F;
i <<= 8;
assert(i == 0xF00);

The left-shift assignment: >>=

mutable i = 0xF00;
i >>= 4;
assert(i == 0x0F0);

The bitwise OR assignment: |=

mutable i = 0xF0;
i |= 0x0F;
assert(i == 0xFF);

The bitwise AND assignment: &=

mutable i = 0xFA;
i &= 0x1F;
assert(i == 0x1A);

The bitwise exclusive-OR (XOR) assignment: ^=

mutable i = 1;
i ^= 0;
assert(i == 1);

i ^= 1;
assert(i == 0);

Exchange values: <->

mutable a = 1;
mutable b = 2;

a <-> b;

assert(a == 2);
assert(b == 1);

List prepend (concatenation): ::=

mutable a = [2, 1];

a ::= 3;

assert(a == [3, 2, 1]);

C# 3.0 like lambds: =>

def a = [2, 1];

def b = a.Map(element => element * 2);

assert(b == [4, 2]);

Use default value if null: ??

def a : int? = null;
def b = a ?? 42;

assert(b == 42);

def a : int? = 88;
def b = a ?? 42;

assert(b == 88);

def a : string = null;
def b = a ?? "default value";

assert(b == "default value");

def a : string = "some value";
def b = a ?? "default value";

assert(b == "some value");

Safe Navigation (Groovy like): ?.

class A { public i : int = 2; }
class B { public a : A = null; }
class C { public a : B = null; }

def b1 = B();

assert(b1?.a?.i == 0); // 0 is a default value of int (type of i field)
Clone this wiki locally