1

I have been trying to understand how mathematica does pattern matching:

{Sin[x] + 1} /. Sin -> Cos

returns

Cos[x] + 1

I am guessing that the program searches for the expression in the expression tree and then replaces the pattern once it finds it.

Thanks

  • From the documentation of ReplaceAll: 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. – vapor Mar 21 '17 at 17:17
  • Thanks for your reply, I have read the documentation. I wanted to know how does it look at each part of the expresison does it traverse down the expression tree or it has some other mechanism? – Arihant Parsoya Mar 21 '17 at 17:32
  • It performs a DFS of the expression tree. (I am not 100% sure since I cannot find an official source) – vapor Mar 21 '17 at 17:46
  • @happyfish It is not always DFS. It is DFS for functions like Replace, Cases, etc. For ReplaceAll it is actually BFS. – Leonid Shifrin Mar 21 '17 at 17:52
  • @LeonidShifrin Thanks for the information! I can't see how BFS is performed with tracing functions (only showing how mma read the expression with DFS, and the replacement is done in one step). Would you mind sharing some details on this observation? – vapor Mar 21 '17 at 17:55
  • 1
    @LeonidShifrin I think ReplaceAll is not a BFS but rather a depth-first preorder traversal? – Mr.Wizard Mar 21 '17 at 18:28
  • @happyfish these might interest you: (9209), (9233), https://en.wikipedia.org/wiki/Tree_traversal – Mr.Wizard Mar 21 '17 at 18:29
  • @happyfish I wrote about this in my book. A few other relevant links are 1 and 2. – Leonid Shifrin Mar 21 '17 at 18:34
  • @Mr.Wizard You may be right. – Leonid Shifrin Mar 21 '17 at 18:39

0 Answers0