Is there a way to write string literals “concatenable”, i.e. “abcd” “efgh” to have a single literal “abcdefgh”? And are there multiline strings like in Python?
Multiline strings are called “here strings” in Racket. Example:
#<<END
A line.
A second line.
END
You can choose a different word than END.
I am not sure what you mean by “contenable string literals”.
The function ~a
can be uses as an easy way to concatenate strings and to convert numbers to strings.
(~a "There are " 42 "apples.")
If you use
`#lang at-exp racket`
you can write:
@~a{There are @(+ 41 1) apples.}
Check Greg’s blog post: https://www.greghendershott.com/2015/08/at-expressions.html
Strings delimited by "
can have newlines in them, too
Concatenable (or better: automatically concatenated) strings can be found e.g. in C, where printf("abcd" "efgh");
concatenates adjacent string literals during parsing
so (~a
comes pretty close to that
In C arguments are separated by comma. So it is not a problem to “foo” “bar” into “foobar”. In Racket arguments are separated by white space, so that’s not an option. However, if you have a long string and want to split it over two lines, you can write as the last character on the line and continue at the next line.
The result is “foobar”.
You can also use normal strings by the way: (define str "This is
a multiline
string")
but it may be considered bad style due to breaking the <https://github.com/google/google-java-format/wiki/The-Rectangle-Rule|’rectangular rule’>. A slightly better style maybe(?): (define str
"\
This is
a multiline
string")
or string-append
?
Yeah, I would suggest using ~a
or string-append
:
(define test
(~a "hello"
"world"))
I used string-append
for that. I didn’t know that the shorter ~a
can do the same. Nice! :slightly_smiling_face:
There is a great blog post that covers using ~a
with #lang at-exp racket
https://www.greghendershott.com/2015/08/at-expressions.html\|https://www.greghendershott.com/2015/08/at-expressions.html
That probably won’t work though. The arguments to ~a
by @
reader will be something like '("hello" "\n" "world")
. So you need something other than ~a
to filter out \n
(and also to decode literal \n
to newline, etc.).