I am a bit confused with how do some expressions in Mathematica get parsed. I was using a combination of map (/@
) and abstract functions of the form F[#, _param_]&
, and ran into the following problem.
This code does not work properly (it seems that G
is not applied):
G[#, _params_]& /@ F[#, _params_]& /@ myList
But if I parenthesize the abstract function F
, it works properly:
G[#, _params_]& /@ (F[#, _params_]&) /@ myList
Also works if i close the parenthesis at the very end.
Why is this happening? Why does the first example not work? When do I need to add parentheses in such chains in general?
As I am not sure how general this issue is, I attach the code where I encountered the problem. I have a list of strings that I imported, and want to first trim it, and then split it (so that I can convert it to expression next)
myList = {" \"2, 3\"", " \"2, 14\""}
In: StringSplit[#, ","] & /@ StringTrim[#, ("\"" | " ") ...] & /@ myList
Out: {"2, 3", "2, 14"}
In: StringSplit[#, ","] & /@ (StringTrim[#, ("\"" | " ") ...] &) /@ myList
Out: {{"2", " 3"}, {"2", " 14"}}
As you can see, in the first case, the StringSplit
was not applied.
G[#] & /@ F[#] & /@ {a, b, c} // Trace
andG[#] & /@ (F[#] &) /@ {a, b, c} // Trace
, you will see how parentheses set the order of computations. $\endgroup$myList // StringReplace[{" " -> "", "\"" -> ""}] // StringSplit[#, ","] & // ToExpression
$\endgroup$[]
, to "parentheses", which are()
. Roll back if you really meant brackets. $\endgroup$&
in the 3rd paragraph here. $\endgroup$