logo

Programming Languages - Operators

Last Updated: 2024-01-21

Mod Operator

% operator

  • Python: returns the modulus and
  • Java: returns the remainder.

They give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.

Example:

  • C++/Java: if you directly calculate -4 % 3 you will get -1. You can use function: a % b = (a % b + b) % b to make it is a non negative integer.
  • Python: you can directly use -1 % 3, you will get 2 automatically.

In Java, the positive value by:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;
  • (a + b) % p = (a % p + b % p) % p
  • (a - b) % p = (a % p - b % p) % p
  • (a * b) % p = (a % p * b % p) % p
  • a ^ b % p = ((a % p)^b) % p

Ternary

Ternary operator: isTrue ? "a" : "b"

No Ternary operator: Python, Rust, Kotlin, Go

Python

There is no ternary operator(condition?a:b) in Python, but can use this

>>> "a" if 1 + 1 == 2 else "b"
'a'
>>> "a" if 1 + 1 > 2 else "b"
'b'

Rust

let result = if isTrue { "a" } else { "b" }

Kotlin

val result = if (isTrue) "a" else "b"

Go

No one-liner alternatives, use if-else.

Elvis Operator

Elvis Operator: ?:. Return the first operand if that operand evaluates to a true value, and otherwise evaluates and returns the second operand.


x = f() ?: g()

This is equivalent to


x = f() ? f() : g()

This is helpful to set a default value, so the returned value is always not null.


x = f() ?: "default value"

Null Coalescing Operator: ??


a ?? b

This is equivalent to


a != null ? a : b

Reading from left to right, the first value which exists and is not null is the value that will be returned.


a ?? b ?? c

The assignment operators and the ternary operator (?:) are right associative. All other binary operators are left associative.

Spread / Unpack Operator

JavaScript

foo(...params);
[...array1, ...array2];

Python

foo(*params)  # positional expansion
foo(**params) # keyword expansion
[*array1, *array2]

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

def sum(a, b):
    return a + b

values = (1, 2)

s = sum(*values)

This will unpack the tuple so that it actually executes as:

s = sum(1, 2)

The double star ** unpacks a dictionary for named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

You can also combine:

def sum(a, b, c, d):
    return a + b + c + d

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)

will execute as:

s = sum(1, 2, c=10, d=15)

Turbofish

Turbofish: ::<>.

Rust

If a function is defined as:

fn foo<A, B>()

You can call it by:

foo::<String, i32>()

Examples:

"2048".parse::<u32>()

[1, 2, 3, 4].iter().collect::<Vec<_>>()
[1, 2, 3, 4].iter().sum::<u32>()
[1, 2, 3, 4].iter().product::<u32>()