Interpolated strings

bpr via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 18 16:58:27 PDT 2017


On Tuesday, 18 April 2017 at 08:01:14 UTC, Jacob Carlborg wrote:
> On 2017-04-18 08:59, Stefan Koch wrote:
>
>> The corresponding ast-macros would be extremely complex
>
> No, it's not that complex.

Here's how it's done in Nim, a statically typed language similar 
to D, but with Python syntax, and macros. It takes some knowledge 
to understand, sure, macros are not a beginner tool, but wouldn't 
say this is extremely complex. I bet a D-with-macros would have a 
similar complexity solution.

------------------------------ string_interpolation.nim 
------------------------------

import macros, parseutils, sequtils

macro exho(text: string{lit}): untyped =
   var nodes: seq[NimNode] = @[]
   # 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.14
   message = exho"$multiplier times 2.5 is ${multiplier * 2.5}"
   foo = "foo"
   message2 = exho"$foo 3 times is ${foo & foo & foo}"

echo message
echo message2
--------------------------------------------------------------------------------

Running gives

3.14 times 2.5 is 7.850000000000001
foo 3 times is foofoofoo





More information about the Digitalmars-d mailing list