"42" + 1
What, if anything, should a mixed-type expression like "42" + 1 mean?
The sanest result is a compile-time error, as in Rust.
| $ cargo check | |
| Checking rust v0.1.0 (/Users/jeff/var/play/rust) | |
| error[E0369]: cannot add `{integer}` to `&str` | |
| --> src/main.rs:2:25 | |
| | | |
| 2 | println!("{}", "42" + 1); | |
| | ---- ^ - {integer} | |
| | | | |
| | &str |
Slightly less sane is a compiler that correctly diagnoses the issue, but nevertheless produces a binary that does something wacky at run-time.
| $ cc main.c | |
| main.c:4:13: warning: adding 'int' to a string does not append to the string [-Wstring-plus-int] | |
| puts("42" + 1); | |
| ~~~~~^~~ | |
| $ ./a.out | |
| 2 |
The next least insane result is a run-time error, as in Python.
| $ python3 -c 'print("42" + 1)' | |
| Traceback (most recent call last): | |
| File "<string>", line 1, in <module> | |
| TypeError: can only concatenate str (not "int") to str |
The most guano crazy thing you could possibly do is to silently and implicitly convert one side of the expression to the other's type, as in Perl or JavaScript.
| $ perl -le 'print "42" + 1' | |
| 43 | |
| $ node -p '"42" + 1' | |
| 421 |
Guess what Java does?
| public class Main { | |
| public static void main(String[] args) { | |
| System.out.println("42" + 1); | |
| } | |
| } |
| $ javac Main.java && java Main | |
| 421 |
Java gives the initial impression of being a strongly typed language, but it has an awful lot of gotchas. In fact, Java is basically a dark room full of razor blades, but we can blunt those blades else-post. For now, simply consider: If you were writing the next big programming language, how would it handle "42" + 1?


hey Jeff! long time! I've been working on some large Perl code bases for a long time now. I have a love/hate relationship with Perl and other Duck-Typed languages. I have seen many bugs over the years that a statically typed compiled language would have prevented outright that I am ready to move back to a compiled/static language. We have officially said "no more Perl" and adopted python to better allow us to find developers! However, for me, Perl->Python is a lateral move. I am hoping to find a way to move to C++ for my next big project.
Sorry that was a bit off topic. I wanted to say that Perl6/Raku seems to have taken things to a whole new level with smart match and other fuzzy features that try to "do the right thing".
The last time I thought about this problem, I had an interesting idea. Start at "compile error", but allow the author to write an explicit override for `+(string, int)` that defines the alternate behavior that is desired, so that if you REALLY want it that way, it's easy for someone else to read what it's doing.