Wishlist-for-R icon indicating copy to clipboard operation
Wishlist-for-R copied to clipboard

Wish: base version of glue::glue()

Open francisbarton opened this issue 9 months ago • 3 comments

It would be neat if there was a function in base that did something like

g("Hello, {user}!")

where g() provides the same functionality as glue::glue(). Strings with variable interpolation support. Always feels like something you shouldn't need to load a whole extra package for.

francisbarton avatar Oct 18 '23 22:10 francisbarton

Even better, instead of a function, it would be great to have special string literals for this, like in Python or JS, or a lot of other languages.

It could have a syntax similar to raw strings, but with an f "marker" instead of r:

f"(Hello {user}!)"

gaborcsardi avatar Oct 19 '23 08:10 gaborcsardi

For reference, Link to discussion on R-devel. Link jumps you to the middle of the discussion where the beginning of a discussion into glue-style string interpolation comes up. Think there are some other similar threads around the same time as well.

TimTaylor avatar Oct 19 '23 08:10 TimTaylor

If there's interest in supporting format strings using a name"string" syntax, I'd prefer if it became user-customizable similar to julia's str macros instead of depending on the base language to implement specific string syntax.

In julia I've seen some pretty interesting use cases including special inline modes for raw strings, version numbers, R, SQL, regex and many more.

Instead of having the base language implement some special formatting, perhaps it could set aside a generic so that you could create your own object to dispatch on:

glue"{a} {b} {c}"
# equivalent to 
# .Primitive("str_format")(glue, "{a} {b} {c}")

Then if glue isn't a function, but an object to capture the formatting settings, then you could implement something like:

str_format.glue(fmt, value) {
  glue::glue(value)
}

This would also mean that you could generate a formatter object with configurable settings:

whisker <- glue::glue_fmt(.open = "{{", .close = "}}")
whisker"hello, {{whisker_user}}!"

dgkf avatar Mar 22 '24 01:03 dgkf