1

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.

Michael E2
  • 235,386
  • 17
  • 334
  • 747
Ondrej Draganov
  • 321
  • 1
  • 8
  • 1
    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. – Alx Nov 24 '19 at 13:25
  • 1
    This avoids ambiguity of pure functions. myList // StringReplace[{" " -> "", "\"" -> ""}] // StringSplit[#, ","] & // ToExpression – Rohit Namjoshi Nov 24 '19 at 14:41
  • 1
    I changed "brackets", which are [], to "parentheses", which are (). Roll back if you really meant brackets. – Michael E2 Nov 24 '19 at 15:21
  • 5
    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. – Michael E2 Nov 24 '19 at 15:23
  • 2
    Syntax highlighting also indicates precedence and syntactical scope of a function in an expression as you move the cursor around. – Michael E2 Nov 25 '19 at 04:10
  • 1
    So the problem here is low precedence of &, makes sense. I'm not really sure why does the version without parentheses work at all now, but I see why does it not do what I want. Thank you for the answers! Also, thanks @Michael for the edit, I meant, indeed, parentheses. – Ondrej Draganov Nov 25 '19 at 08:44
  • The answer is essentially there, so I guess we can mark it as duplicate – Ondrej Draganov Nov 25 '19 at 17:03

0 Answers0