In scala, you easily include the content of a variable inside a string, like this:
val nm = "Arrr"
println(s"my name is , $nm")
Is this possible in nim, and in that case, how?
In scala, you easily include the content of a variable inside a string, like this:
val nm = "Arrr"
println(s"my name is , $nm")
Is this possible in nim, and in that case, how?
The strfmt module features some experimental string interpolation:
import strfmt
let nm = "Arrr"
echo interp"my name is $nm"
Adding your own string interpolation is not particularly had, since the standard library already provides most of the necessary pieces:
import macros, parseutils, sequtils
macro i(text: string{lit}): expr =
var nodes: seq[PNimrodNode] = @[]
# Parse string literal into "stuff".
for k, v in text.strVal.interpolatedFragments:
if k == ikStr or k == ikDollar:
nodes.add(newLit(v))
else:
nodes.add(parseExpr("$(" & v & ")"))
# Fold individual nodes into a statement list.
result = newNimNode(nnkStmtList).add(
foldr(nodes, a.infix("&", b)))
const
multiplier = 3
message = i"$multiplier times 2.5 is ${multiplier * 2.5}"
echo message
# --> 3 times 2.5 is 7.5
proc blurb(a: int): string =
result = i"param a ($a) is not a constant"
when isMainModule:
for f in 1..10:
echo f.blurb
interpolatedFragments
will break on something like "${a & "}" & b}
, since it only counts braces. strfmt
currently also suffers from this, but there should be a way to solve it by making interpolatedFragments
a compileTime
iterator, allowing to use parseExpr
to properly parse an expression. –
Ravine interpolatedFragments
is very simple and wasn't intended for nested braces. Nothing stops you from implementing a brace escaping mechanism inside the parsing loop and making it on par to say an SQL parser like github.com/Araq/Nim/blob/devel/lib/pure/parsesql.nim. But at this point I'd say you are abusing string interpolation for little benefit. –
Ithaca The strformat module is now considered the go-to way to do it:
import strformat
let nm = "Arrr"
echo fmt"my name is , {nm}"
© 2022 - 2024 — McMap. All rights reserved.