+for string concatenation is an unfortunate decision, because:
- String concatenation is noncommutative unlike addition operator
+
. This argument mentions the developers of Julia programming language:
https://docs.julialang.org/en/latest/manual/...:
And I suggest to make operator
In mathematics,+
usually denotes a commutative operation, where the order of the operands does not matter. An example of this is matrix addition, whereA + B == B + A
for any matricesA
andB
that have the same shape.+
strictly commutative and in presence ofF +(MyType, Int)
forbidF +(Int, MyType)
. This will reduce a work of definition of additional/extra operators' overloadings, and at the same time this will increase the predictability of programs [{…}]. - In some languages (for example in PHP and Perl) "5"+5 yields 10.
Dart Puzzlers: Chapter 2:
Or more vital example:
Can you guess what the following statement prints?
System.out.println("2 + 2 = " + 2+2);
Translating this mini-puzzle into Dart, we get:
print('2 + 2 = ' + 2+2);
Both the Java and Dart versions print2 + 2 = 22
, which may not be what you expected.
print("id=" + id+1)
Dart Puzzlers: Chapter 2:
This [as in 3] problem is solved with a separate string concatenation operator, because its priority may be lower than of operator
... System.out.println("Animals are equal: " + pig == dog); ...
It doesn't printAnimals are equal: true
. It doesn't printAnimals are equal: false
, either. It just printsfalse
. Why? Because the+
operator binds tighter than the==
operator.==
.
For this [and/or some other] reasons operator
+is not used for string concatenation in many languages (PHP, Perl, D, Lua, Julia, Visual Basic, Nim, Dart), but definitive designation for this operation is still not found [{…}], therefore I decided to go another way and reject a dedicated operator for string concatenation. To concat string literal and variable in 11l just place it next to each other without spaces:
print("id="id) print("id="(id+1))To concat two variables use this notation:
print(name""value)or this:
print(name‘’value)In the last case a raw string literal is used — raw strings should be enclosed in single quotation marks: characters
‘and
’.
Consecutive string literals [of one type (‘’ or "")] are not concatenated [unlike in languages C or Python], because it is error prone {…} — space between two string literals indicate that likely comma is missed here.
String literals are concatenated only with variables:
‘Value = ’value"\n", and with string literals of other type:
‘no-break’"\xA0"‘space’. And in this case there should not be a space between string literal and a variable or string literal of other type.
Why isBecause+bad for strings, but*is not?
*almost always has one of the operands as a string literal [
"s" * n/
n * "s"] and such an operation is easily noticeable.