5 ms·
I really, really wish people would stop using + for string concatenation in new languages they design. It shares only a tangential relationship to arithmetic a
by kbenson 8y ago
I really, really wish people would stop using + for string concatenation in new languages they design. It shares only a tangential relationship to arithmetic addition, and even that's a stretch. It's caused an enormous amount of bugs in numerous different languages. Please, let's just let that concept die for newer languages.
- dbaupp 8y agoDo you have examples of bugs that it causes when more strictly typed? That is, string + number is an error.
- kbenson 8y agoIn those languages, it's more a cognitive mismatch (usually covered up as it's what people learned it as). Even then, people seem to think of + as a special case, and in a language that is otherwise very strictly typed will decide to automatically convert between different numeric types (floating point and integer, for example). That's admittedly a different problem, but it shares a lot in common with what I originally mentioned.
- oblio 8y agoI personally like forms of string interpolation: NSString three = f”{one} {two}”; Readable and should be efficient.
- derefr 8y ago> It shares only a tangential relationship to arithmetic addition You’re right—string concatenation is not addition, it’s multiplication. (Contrast “sum types” and “product types” for an intuition, if you don’t have an education in abstract algebra.)
- chriswarbo 8y agoI'd disagree and say that it's value-level addition. Adding the number `3` to the number `5` gives us a single number `8`, not a pair of `3` and `5`. Likewise appending `"hello "` to `"world"` gives us a single string `"hello world"` not a pair of strings. If we model arithmetic addition with Peano numerals, that would be: three = S (S (S Z)) five = S (S (S (S (S Z)))) eight = plus three five = S (S (S (S (S (S (S (S Z))))))) We can model strings as lists of characters (which Haskell does, but is inefficient). It's essentially the same except the second constructor takes a character as argument: hello = Cons 'h' (Cons 'e' (Cons 'l' (Cons 'l' (Cons 'o' (Cons ' ' Nil))))) world = Cons 'w' (Cons 'o' (Cons 'r' (Cons 'l' (Cons 'd' Nil)))) greet = append hello world = Cons 'h' (Cons 'e' (Cons 'l' (Cons 'l' (Cons 'o' (Cons ' ' Cons 'w' (Cons 'o' (Cons 'r' (Cons 'l' (Cons 'd' Nil))))))))) The algorithms for adding Peano numerals and appending lists of characters are identical: plus Z y = y plus (S x) y = S (plus x y) append Nil y = y append (Cons x xs) y = Cons x (append xs y) If we replace 'Char' with '()' (i.e. `List ()` or `[()`]) then they're isomorphic. I wrote up some thoughts about this connection at http://chriswarbo.net/blog/2014-12-04-Nat_like_types.html http://chriswarbo.net/blog/2014-12-04-Nat_like_types.html
- st1ck 8y agoYou'd use `<>` or `++` in Haskell for strings, lists or whatever other instances of Semigroup or Monoid type classes.