How to convert a string to an expression using ToExpression [], how to prevent evaluation of the result?

I have the following line:

"{f[{-1 + x, y}]; f[{1 + x, y}]; f[{x, 1 + y}]}" 

And I want to convert it to expression (s). Directly applying ToExpression gives only the latter, i.e. {f[{x, 1 + y}]} . How to get the whole list?

+4
source share
2 answers

You can check the ToExpression documentation to find your third argument, and use

 ToExpression["{f[{-1 + x, y}]; f[{1 + x, y}]; f[{x, 1 + y}]}", InputForm, Hold] 

to prevent evaluation.

Several functions that convert expressions or extract parts ( Extract , Level , etc.) have the ability to wrap the extracted part in an arbitrary function. A common use is to wrap them in Hold , preventing pricing.


EDIT: Note that your expression is not a list. This is a CompoundExpression . You may be looking for

 ToExpression["{f[{-1 + x, y}]; f[{1 + x, y}]; f[{x, 1 + y}]}", InputForm, Hold] /. CompoundExpression -> List // ReleaseHold 

Can you explain what you are trying to achieve, and where did you get the line?

+8
source

In fact, ToExpression converts the entire string to an expression, as you expected. In the following example

 In[1]:= ToExpression["a=1;b=2"] Out[1]= 2 In[2]:= a Out[2]= 1 

you can see that the first part of a=1 was correctly evaluated as part of the CompoundExpression .

You may need to convert expressions separated by semicolons to a list of expressions. You can use StringSplit for this:

 In[3]:= ToExpressionList[s_String] := ToExpression /@ StringSplit[s, ";"] In[4]:= ToExpressionList["x;y"] Out[4]= {x,y} 

Edit: It looks like you are trying to use a semicolon as a separator.In Mathematica list you will need to use , for this. So, you can also achieve what you want by replacing with ; into your string and then apply ToExpression afterwards:

 In[20] := ToExpression @ StringReplace[ "{f[{-1 + x, y}]; f[{1 + x, y}]; f[{x, 1 + y}]}", ";" -> "," ] Out[20] = {f({x-1,y}),f({x+1,y}),f({x,y+1})} 
+1
source

Source: https://habr.com/ru/post/1388750/


All Articles