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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With