# Defining functions from strings

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

"g[q[1]_ \[TensorProduct] q[2]_ \[TensorProduct] q[3]_ \[TensorProduct] q[4]_]"


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.

• 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

If it is easy for you to construct strings like

"g[q[1]_ \[TensorProduct] q[2]_ \[TensorProduct] q[3]_ \[TensorProduct] q[4]_]"


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[1], q[2] , q[3] , q[4]};


you could do

(ToString@#[[0]] <> ToString@#[[1]] <> "_") & /@ 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[1] \[TensorProduct] q[2] \[TensorProduct] q[3] \[TensorProduct] q[4] ];


note that internally it looks like

fun // FullForm


g[TensorProduct[q[1],q[2],q[3],q[4]]]

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

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


so that

fun[[1]] = patternize /@ fun[[1]]


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[1] works!. Now the program works perfectly fine! – David Davalos Jun 27 '19 at 16:06