1
$\begingroup$

Consider the following setup:

ClearAll[f,g];

g[string_]:=TemplateApply[
    StringTemplate@string,
    <|"product"->Symbol["product"]|>
];

f[product_]:=g["This is a test `product` for package!"];

My actual g function is more general and finds the template slots in the string and replaces slot SlotName by Symbol["SlotName"]. But the issue I am facing is the arguments are provided via DownValues and so are not getting detected. How do I make it work?

f["PROD"]

produces:

"This is a test product for package!"

But I want:

"This is a test PROD for package!"

Is there a construct SendArguments that can pass DownValue patterns further down?

g[string_,ReceiveArguments[]]:=TemplateApply[
    StringTemplate@string,
    <|"product"->product|>
];

f[product_]:=g["This is a test `product` for package!",SendArguments[]];

How to do this? Wolfram is a symbolic language so there must be a way to achieve this?

$\endgroup$
1
  • $\begingroup$ Are you expecting Symbol["SlotName"] to somehow create a "local" symbol and have it be bound to an argument passed in to g? $\endgroup$
    – lericr
    Feb 27 at 4:17

2 Answers 2

1
$\begingroup$

I feel like I must be missing something, because it sounds like you just want a straightforward passing of arguments:

g[string_, productReplacement_] := 
  TemplateApply[StringTemplate@string, <|"product" -> productReplacement|>];
f[product_] := g["This is a test `product` for package!", product];

f["PROD"]
(* "This is a test PROD for package!" *)
$\endgroup$
0
$\begingroup$

I really think this is a bad idea, but if you truly want "implicit", you may need to let your special symbols live "outside" your functions. You could do this by setting up a special context, or you could go ahead and use the Global context, but in that case you might want to Protect them.

(* Using Global context, but trying to be safe *)
Protect[product];
g[string_] := TemplateApply[StringTemplate@string, <|"product" -> product|>];
f[productReplacement_] := 
  Block[
    {product = productReplacement}, 
    g["This is a test `product` for package!"]];

f["PROD"]
(* "This is a test PROD for package!" *)


(* Using a "private" context *)
ClearAll[f, g];
g[string_] := TemplateApply[StringTemplate@string, <|"product" -> Arguments`product|>];
f[productReplacement_] := 
  Block[
    {Arguments`product = productReplacement}, 
    g["This is a test `product` for package!"]];

(* Alternative, but same basic idea *)
ClearAll[f, g];

g[string_] := TemplateApply[StringTemplate@string, <|"product" -> Arguments`product|>];
f[productReplacement_] := 
  (Arguments`product = productReplacement; g["This is a test `product` for package!"]);
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.