mathjs icon indicating copy to clipboard operation
mathjs copied to clipboard

string concatenation doc issue and questions

Open gwhitney opened this issue 10 months ago • 1 comments

Describe the bug The page https://mathjs.org/docs/datatypes/index.html includes the example math.add('hello ', 'world') with the expected return value 'hello world' but this fails. It has the example math.max('A', 'D', 'C'), but this also fails.

Of the types listed on that page, only Boolean and String do not have their own page. Should String? I think so, because (a) strings are a common and important datatype, and (b) there are some subtleties with mathjs strings, as the first example shows. Should Boolean as well, just for the sake of uniformity/thoroughness?

The doc page for concat does not mention string in the text, nor in the possible typings. It does show one string example. But strings are not Array | Matrix in the mathjs type system. So this documentation should be corrected as well.

And should we hack the doc page generation so that concat appears both in the Matrix and String section of the function reference? Are there any other Matrix methods that work for string as well?

Clearly 'a' + 'b' used to work in the expression language. It's been removed for good reason, but concat('a', 'b') is a bit cumbersome. Should we introduce a (string and/or array/Matrix) concatenation operator (that would presumably coerce its operands to (strings and/or arrays/Matrices, as appropriate)? If so, what should the operator be? Possibilities that come to mind are:

  • ++, if one is willing to require 7 + +5 to have to have the space between the two plus symbols (I certainly would be, because it is super rare for unary + to be useful);
  • .+ by very rough analogy with .* and ./ -- it is not elementwise addition, because ordinary matrix addition already is elementwise, but it is the "other sort of addition you might want to do" just like .* is the "other sort of multiplication you might want to do"; or
  • && because we are not using this for logical and, so it is open.

There may be other reasonable possibilities.

To Reproduce math.add('hello ', 'world') --> Throws Error: cannot convert 'hello ' to number math.max('A', 'D', 'C') --> Throws Error: cannot convert 'D' to number

gwhitney avatar Feb 22 '25 02:02 gwhitney

I've addressed the broken examples via de7865c69a5bbf866b7587b58038be9c75b7e0db

Good idea to create pages for String and Boolean. About booleans there is not much to tell, but it will be good to explain how strings are handled normally (i.e. parsed into a numeric value and then used)

Using concat(a, b) to concatenate strings is indeed cumbersome. So far I haven't heard any complaints about it. I think it is an edge case, and that it is acceptable that this edge case is a bit verbose (at least there is a solution that works fine).

josdejong avatar May 21 '25 15:05 josdejong