Re: Factor

Factor: the language, the theory, and the practice.

Interpolate Formatting

Tuesday, June 4, 2024

I wrote almost a decade ago about some minor improvements to the interpolate vocabulary in Factor. This vocabulary provides support for “interpolating variable values into strings” – using words such as interpolate as well as the more recently added interpolate string syntax I" ".

Recently, I added support for format directives such as those used in our formatting vocabulary. This required a change to split out a format-directive EBNF and then I could allow format directives to be used in interpolate forms.

The result is something that works a lot more like formatted string literals in Python:

IN: scratchpad USE: interpolate

IN: scratchpad 1.2345 "${:011.5f}" interpolate
00001.23450

IN: scratchpad 1 ..= 11 [| x |
                   x dup x * dup x *
                   "${:2d} ${:3d} ${:4d}\n" interpolate
               ] each
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
11 121 1331

IN: scratchpad H{ { "n" 42 } } [
                   "Hello, Worker #${n:06x}!" interpolate
               ] with-variables
Hello, Worker #00002a!

Perhaps we can add some support for the name= directive, inline factor code instead of always stack and namespace variables, and other features that might be useful from f-string literals and other format libraries.

This is available in a recent nightly build!