![]() |
| ||||||||||||||||||||
Navigation |
Synopsis String values.
Syntax
"StringChar1StringChar2..."
where StringChar may be one of the following:
Types
str
Details Concatenation Equal GreaterThan GreaterThanOrEqual LessThan LessThanOrEqual NotEqual Slice Subscription
Description The string values are represented by the type
str and consist of character
sequences surrounded by double quotes, e.g., "a" or "a\nlong\nstring" .
Multiline: Strings may span more than one line. The margin character ' indicates which part of a line will be ignored. This is useful for indenting a multi-line string with the source code that generates it.
Interpolation: String literals support so-called string interpolation: inside string constants text between angle brackets ( < and > ) is first executed and then replaced by
its string value.
Various statements (if, for, while, do) also return a value and can be used in this way.
In the interpolation variant of these statements the block or blocks that are part of the statement become arbitrary text
(that may itself contain interpolations).
Auto-indent: Expressions that get interpolated in a string will be auto-indented. This means that each line that results from the evaluation of the expression is prefixed with the indentation level of the position of the expression in the current string. The following functions are provided for strings:
Examples
rascal>N = 13; int: 13 rascal>"The value of N is <N>"; str: "The value of N is 13" rascal>"The value of N*N is <N*N>"; str: "The value of N*N is 169" rascal>"The value is <(N < 10) ? 10 : N*N>"; str: "The value is 169"As you can see the string value of variables and expressions is interpolated in the result as expected. Some examples of more advances string interpolation rascal>"N is <if(N < 10){> small <} else {> large <}>"; str: "N is large " rascal>"N is <if(N < 10){> small <} else {> large (<N>)<}>"; str: "N is large (13)" rascal>"before <for(x<-[1..5]){>a <x> b <}>after"; str: "before a 1 b a 2 b a 3 b a 4 b after"multi-line string rascal>import IO; ok rascal>println("hello >>>>>>>this >>>>>>> is >>>>>>> new") hello this is new okmulti-line string with margin: rascal>if (true) >>>>>>> println("this is >>>>>>> 'what >>>>>>> ' margins >>>>>>> 'are good for >>>>>>> "); this is what margins are good for okauto indent: rascal>str genMethod(str n) = "int <n>() { >>>>>>> ' return 0; >>>>>>> '}"; str (str): str genMethod(str); rascal>str genClass() = "class myClass { >>>>>>> ' <genMethod("myMethod")> >>>>>>> '}"; str (): str genClass(); rascal>println(genClass()); class myClass { int myMethod() { return 0; } } ok
Benefits String interpolation enables very flexible template-based text generation as used in generators for
source code, markup and the like.
![]() |