Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation

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?

like image 764
Arrrrrrr Avatar asked Apr 17 '15 16:04

Arrrrrrr


2 Answers

The strfmt module features some experimental string interpolation:

import strfmt
let nm = "Arrr"
echo interp"my name is $nm"
like image 153
def- Avatar answered Sep 23 '22 23:09

def-


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
like image 27
Grzegorz Adam Hankiewicz Avatar answered Sep 22 '22 23:09

Grzegorz Adam Hankiewicz