1
$\begingroup$

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.

$\endgroup$
7
  • 1
    $\begingroup$ Compare results of G[#] & /@ F[#] & /@ {a, b, c} // Trace and G[#] & /@ (F[#] &) /@ {a, b, c} // Trace, you will see how parentheses set the order of computations. $\endgroup$
    – Alx
    Nov 24, 2019 at 13:25
  • 1
    $\begingroup$ This avoids ambiguity of pure functions. myList // StringReplace[{" " -> "", "\"" -> ""}] // StringSplit[#, ","] & // ToExpression $\endgroup$ Nov 24, 2019 at 14:41
  • 1
    $\begingroup$ I changed "brackets", which are [], to "parentheses", which are (). Roll back if you really meant brackets. $\endgroup$
    – Michael E2
    Nov 24, 2019 at 15:21
  • 5
    $\begingroup$ It is a question of precedence. See this answer for references and general discussion. It is also mentioned specifically about & in the 3rd paragraph here. $\endgroup$
    – Michael E2
    Nov 24, 2019 at 15:23
  • 2
    $\begingroup$ Syntax highlighting also indicates precedence and syntactical scope of a function in an expression as you move the cursor around. $\endgroup$
    – Michael E2
    Nov 25, 2019 at 4:10

0

Browse other questions tagged or ask your own question.