I'm sorry but I still have problem to understand, here is the code I consider :
expr = g[g[x]];
ReplaceAll[expr, g -> fonction]
ReplaceAll[expr, g[x_] -> fonction[x]]
fonction[fonction[x]]
fonction[g[x]]
I will write what I understand step by step of what is happening : the first ReplaceAll : ReplaceAll[expr, g -> fonction]
ReplaceAll looks at each part of expr, tries all the rules on it, and then goes on to the next part of expr. The first rule that applies to a particular part is used; no further rules are tried on that part or on any of its subparts.
Allright, I will look at each part of expr.
- I look at the 0'th part of expr which is the Head : g. I have a matching pattern, g becomes fonction. I don't have to look at subparts of g as I had a matching (but even in this case, g doesn't have subparts so it wouldn't change anything).
- I go at the next part (1st part) of expr : fonction[g[x]][[1]] = g[x] it doesn't match.
- I go at the first subpart of g[x] : g[x][[0]] = g, it matches. I replace. I don't have to look at the subparts of g as it matched. At this point I thus have fonction[fonction[x]]
- I look at the 2ndt part of expr : fonction[fonction[x]][[2]] : it doesn't exist.
Thus the code stops and the function returns : fonction[fonction[x]]
Now for the second ReplaceAll : ReplaceAll[expr, g[x_] -> fonction[x]]
- I look at the 0'th part of expr : g[g[x]][[0]] = g : no matching
- I look at the subparts of g : it doesn't have, so it stops for that.
- Thus, now I look at the 1st part of expr : g[g[x]][[1]] = g[x] It matches : g[x] -> fonction[x]. I thus now have g[fonction[x]]... which I know is wrong.
Here is how I understood the algorithm and I still have a problem. I don't understand what precisely does the algorithm then.
And is the 0'th part really the head or the full expression ? Because in the documentation of Replace for example :
The default value for levelspec in Replace is {0}, corresponding to the whole expression.