# Defining functions from strings

Blank symbol (_) is moved when applying ToExpression to the following string:

"g[q_ \[TensorProduct] q_ \[TensorProduct] q_ \[TensorProduct] q_]"


I want to define many functions, with varying arguments and forms, so it is easy to me to construct first the strings. If you have another solution to my problem it will be welcome. Basically I want to define functions from their arguments automatically.

Thanks in advance.

• What are you expecting ToExpression applied to that string to evaluate to? – Rohit Namjoshi Jun 26 '19 at 7:31
• Mathematica's pretty useful for writing functions to create other functions. It's not immediately clear why you are trying to write strings to then transform to expressions. Perhaps you can explain a little further what you are really trying to do. – High Performance Mark Jun 26 '19 at 7:36
• This sounds like a textbook XY problem. – Roman Jun 27 '19 at 7:45

## 1 Answer

If it is easy for you to construct strings like

"g[q_ \[TensorProduct] q_ \[TensorProduct] q_ \[TensorProduct] q_]"


consider dropping the [ and ] brackets for each q, so that you end up with

"g[q1_ \[TensorProduct] q2_ \[TensorProduct] q3_ \[TensorProduct] q4_]"


then it will behave as you want.

For example, given a list of potential function arguments

list = {q, q , q , q};


you could do

(ToString@#[] <> ToString@#[] <> "_") & /@ list


{"q1_", "q2_", "q3_", "q4_"}

Additionally, if your wrapper g already implies the \[TensorProduct] for all entries, you could simply use a comma separator g[a,b,c,d] etc. which might make things more stable.

EDIT:

A little example: Starting from a function with an explicit argument

fun = g[q \[TensorProduct] q \[TensorProduct] q \[TensorProduct] q ];


note that internally it looks like

fun // FullForm


g[TensorProduct[q,q,q,q]]

So we can turn the arguments into a pattern by using a custom function like

patternize[in_]:= ToExpression@(ToString@in[] <> ToString@in[] <>  "_")


so that

fun[] = patternize /@ fun[]


q1_\[TensorProduct]q2_\[TensorProduct]q3_\[TensorProduct]q4_

and

fun


g[q1_\[TensorProduct]q2_\[TensorProduct]q3_\[TensorProduct]q4_]

• Thanks a lot!, actually I realized little after that q1 instead of q works!. Now the program works perfectly fine! – David Davalos Jun 27 '19 at 16:06