[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.10.4 String interpolation

The term "string interpolation" is used in various scripting languages such as Perl and Python to refer to the feature to embed expressions in a string literal, which are evaluated and then their results are inserted into the string literal at run time.

Scheme doesn't define such a feature, but Gauche implements it as a reader macro.

Reader syntax: #`string-literal
Evaluates to a string. If string-literal contains the character sequence ,expr, where expr is a valid external representation of a Scheme expression, expr is evaluated and its result is inserted in the original place (by using x->string, see 6.10.3 String Constructors).

The comma and the following expression must be adjacent (without containing any whitespace characters), or it is not recognized as a special sequence.

Two adjacent commas are converted to a single comma. You can embed a comma before a non-whitespace character in string-literal by this.

Other characters in the string-literal are copied as is.

If you use a variable as expr and need to delimit it from the subsequent string, you can use the symbol escape syntax using `|' character, as shown in the last two examples below.

 
#`"This is Gauche, version ,(gauche-version)."
 => "This is Gauche, version 0.6.5."

#`"Date: ,(sys-strftime \"%Y/%m/%d\" (sys-localtime (sys-time)))"
 => "Date: 2002/02/18"

(let ((a "AAA")
      (b "BBB"))
 #`"xxx ,a ,b zzz")
 => "xxx AAA BBB zzz"

#`"123,,456,,789"
 => "123,456,789"

(let ((n 5)) #`"R,|n|RS")
 => "R5RS"

(let ((x "bar")) #`"foo,|x|.")
 => "foobar"

In fact, the reader expands this syntax into a macro call, which is then expanded into a call of string-append as follows:
 
#`"This is Gauche, version ,(gauche-version)."
 ==
(string-append "This is Gauche, version "
               (x->string (gauche-version))
               ".")

Rationale of the syntax: Some other scripting languages use `$expr' or '#{...}'. I chose this syntax with respect to the quasiquote (See section 4.9 Quasiquotation). Althogh it may be awkward to delimit variable names by `|', the comma syntax should be easier to read than the other exotic syntax for seasoned Scheme programmers.

Note that Scheme allows wider range of characters for valid identifier names than usual scripting languages. Consequently, you will almost always need to use `|' delimiters when you interpolate the value of a variable. For example, while you can write "$year/$month/$day $hour:$minutes:$seconds" in Perl, you should write #`",|year|/,|month|/,day ,|hour|:,|minutes|:,seconds". It may be better always to delimit direct variable references in this syntax to avoid confusion.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Ken Dickey on November, 28 2002 using texi2html