# Convert an expression's symbols of form a$x to a[x] I want a function that takes expressions of the following form: a$x and converts them to a[x].

In particular, consider the following test cases

exp = a$x + b$x$y + a$x[d] + a$x[d$y]


Should become, with some ToFunctionNotation:

ToFunctionNotation[exp] == a[x] + b[x][y] + a[x][d] + a[x][d[y]]


Note: I want to keep this as an expression for further processing. I tried using matches with SymbolName and string patterns, but couldn't figure it out.

-
Do they have values? – Kuba Jun 12 '14 at 16:43
Nope. In reality what I am doing is using $ for the naming of the variables, then using mathematica.stackexchange.com/questions/30884/… for display and LaTex output (i.e., a$x -> $a_x$ after the Notation is used. – jlperla Jun 12 '14 at 16:45
Shucks, a simple StringReplace[exp, "$" -> "@"] does not result in your stated precedence ;-( – Yves Klett Jun 12 '14 at 16:45 One possible simplification: I only need 2 levels deep, e.g. b$x$y -> b[x][y] – jlperla Jun 12 '14 at 16:51 Don't use these symbol names. Forms such as a$1 are used internally. If you use it yourself, it might lead to conflicts and random breakage. Generally, it's a bad idea to try to manipulate code as strings (e.g. rewrite names programmatically) in Mathematica. Expression rewriting is almost always better than string rewriting. – Szabolcs Jun 12 '14 at 17:12

Keep in mind Szabolcs comment.

But if it is about string manipulation exercise:

exp2 = "a$x+b$x$y+a$x[d]+a$x[d$y]";

patt = (NumberString | LetterCharacter) ..;

StringReplace[exp2,
x : ((patt ~~ "$") .. ~~ patt ) :> StringJoin @@ Riffle[StringSplit[x, "$" -> "["], "]", {4, -1, 3}]]

"a[x]+b[x][y]+a[x][d]+a[x][d[y]]"


Edit

exp = a$x + b$x$y + a$x[d] + a$x[d$y];
exp /. s_Symbol /; StringMatchQ[SymbolName[s], "*$*"] :> ToExpression[ StringJoin @@ Riffle[StringSplit[SymbolName[s], "$" -> "["], "]", {4, -1, 3}]]

a[x] + a[x][d] + a[x][d[y]] + b[x][y]

-
I need this to work on, and then stay as, the expression tree, rather than a string. Is that possible? – jlperla Jun 12 '14 at 18:01
@jlperla at some point you will have to work with string imo. but maybe not :P I don't know. Here you can exp2 = ToString[exp] and use ToExpression at the end. Only if those symbols have no values. – Kuba Jun 12 '14 at 18:34
Is there any way to use a Replace with a pattern matching on the symbol, which then does the transformation only on that node in the expression tree? For example, p_Symbol?StringMatchQ[SymbolName[p], "\$"] :> ???????  – jlperla Jun 12 '14 at 19:10
@jlperla is my edit what you are after? – Kuba Jun 12 '14 at 19:13
Perfect, that is it. Seems to work with arbitrary expression trees, and I can't see any issues. Thanks. – jlperla Jun 12 '14 at 20:16