TL;DR: The comma operator has little use in D, but perhaps it could be used like in Python, to define tuple expressions.
Context:
In D, one can write a comma expression, similar to C and C++: https://dlang.org/spec/expression.html#comma_expression
Comma itself is a low precedence operator, lower than assignment. Thus, consider the following two C examples:
#include <stdio.h>
int main() {
int a;
a = 1, 2, 3;
printf("%d\n", a); // Outputs: 1
return 0;
}
#include <stdio.h>
int main() {
int a;
a = (1, 2, 3);
printf("%d\n", a); // Outputs: 3
return 0;
}
The usage of the comma operator like this is counter-intuitive, and almost always leads to errors. In fact, in D, using the result of a comma expression is entirely forbidden.
void main()
{
int b = (1, 2, 3);
assert(b == 3);
}
// onlineapp.d(3): Error: using the result of a comma expression is not allowed
The comma expression is mostly viewed as a shortcut to write multiple expressions on a single line, offering only a few benefits over just using semi-colons. For example:
int a = 1; int b = 2;
int a = 1, b = 2; // The type doesn't have to be repeated.
Comparison with Python:
In Python, tuples are a built-in type, defined using parenthesis. E.g. (1, 2, 3)
is a tuple with three numbers, while (3, "Bob", 1.2)
is a tuple with a number, string, and float. https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
The parenthesis are actually optional in Python, meaning one can create a tuple like 1, 2, 3
. Moreover, tuples can be used in assignment expressions as well, as illustrated in the following example:
# Assigns a=1, b=2, c=3
a, b, c = 1, 2, 3
Additionally, tuples can also be used as the return type of functions, e.g.:
# Computes the evaluation of an expression given variable values, and returns
# the result as well as the derivative.
def evalAndDiv(expression, variables):
...
return result, derivative
r,d = evalAndDiv(myExpression, myVariables)
A built-in recognition of tuples also dove-tails nicely with things like foreach
loops, which currently have a special implementation for iterating over associative-arrays: https://dlang.org/spec/hash-map.html#aa_example_iteration
Question: Would D benefit from using commas to define tuples rather than triggering an error when the result of a comma-expression is used? Right now, because the errors, the result of a comma expression is a bit of "unused real estate" in the language.
The easy syntax for dealing with tuples of values is especially useful in writing logic for machine-learning algorithms, and has helped Python gain and hold a strong foothold in this area, but where performance is needed, Python libraries like PyTorch turn to C++. Perhaps this could be D instead.