5.1 Printing Strings and Other Values
One way to print a value to have it be the result of an expression that is immediately with a module body.
"Hello, World!" // prints "Hello, World!" (with quotes) when run
This implicit printing uses #'expr mode, which prints a value as an expression that would produce that value. The print function, in contrast, uses #'text mode by default, which prints a string by writing the individual characters that make up the string.
In documentation examples, printed results are shown in blue, and explicitly printed text is shown in purple. There is no visible distinction when running Rhombus programs.
> "Hello, World!"
"Hello, World!"
> print("Hello, World!")
Hello, World!
"Hello, World!"
> show("Hello, World!")
"Hello, World!"
As the last example illustrates, show is the same as print, but using #'expr mode.
Among predefined datatypes, only strings, byte strings, symbols, and syntax objects print differently in #'text mode versus #'expr mode. A predefined compound datatype, such as a list or map, prints the same in both modes, always printing elements of the compound datatype in #'expr mode. A classes that implement the Printable interface can make different choices based on the mode argument given to its describe method.
> print("apple")
apple
> print(["apple", "banana", "cherry"])
["apple", "banana", "cherry"]
The print and show functions accept any number of arguments and print each of them with a space in between. The println and showln functions are also the same, but print a newline after all arguments. Interactive evaluation adds a newline if needed before a > prompt, so we need to use a block with multiple print calls to demonstrate.
> block:
print("hello", "there", "world")
print("next")
hello there worldnext
> block:
println("hello", "there", "world")
print("next")
hello there world
next
To combine multiple strings and other values into a single string for printing, one strategy is to use the +& operator, which coerces its arguments to strings and then appends the strings.
Hello, World!
I have 5 fingers
For building any significant amount of text, a string interpolation form (see String Interpolation) is usually a better choice than a complex +& combination.
The +& operator implicity uses the to_string function, which is equivalent to printing to a string buffer and then returning the content of that buffer as a new string. Like print, to_string accepts a ~mode argument that defaults to #'text. The repr function is analogous to show, but it produces a string like to_string.
> to_string(42)
"42"
> to_string("apple")
"apple"
"\"apple\""
> repr("apple")
"\"apple\""
"my favorite string is \"apple\""