title: OCaml: Match expression inside another one?
body: <p>I'm currently working on a small project with OCaml; a simple mathematical expression simplifier. I'm supposed to find certain patterns inside an expression, and simplify them so the number of parenthesis inside the expression decreases. So far I've been able to implement most rules except two, for which I've decided to create a recursive, pattern-matching "filter" function. The two rules I need to implement are:</p>
  
  <p>-Turn all expressions of the form a - (b + c) or similar into a - b - c</p>
  
  <p>-Turn all expressions of the form a / (b * c) or similar into a / b / c</p>
  
  <p>...which I suspect would be fairly simple, and once I've managed to implement one, I can implement the other easily. However, I'm having trouble with the recursive pattern-matching function. My type expression is this:</p>
  
  <pre><code>type expr =
   | Var of string            (* variable *)
   | Sum of expr * expr       (* sum  *)
   | Diff of expr * expr      (* difference *)
   | Prod of expr * expr      (* product *)
   | Quot of expr * expr      (* quotient *)
  ;;
  </code></pre>
  
  <p>And what I'm mainly having trouble on, is in the match expression. For example, I'm trying something like this:</p>
  
  <pre><code>let rec filter exp =   
      match exp with       
      | Var v -&gt; Var v                        
      | Sum(e1, e2) -&gt; Sum(e1, e2)          
      | Prod(e1, e2) -&gt; Prod(e1, e2)
      | Diff(e1, e2) -&gt;
          match e2 with
          | Sum(e3, e4) -&gt; filter (diffRule e2)
          | Diff(e3, e4) -&gt; filter (diffRule e2)      
          | _ -&gt; filter e2         
      | Quot(e1, e2) -&gt;                                 ***this line***
          match e2 with  
          | Quot(e3, e4) -&gt; filter (quotRule e2)        
          | Prod(e3, e4) -&gt; filter (quotRule e2)        
          | _ -&gt; filter e2
  ;;
  </code></pre>
  
  <p>However, it seems that the match expression on the marked line is being recognized as being part of the previous "inner match" instead of the "principal match", so all "Quot(...)" expressions are never recognized. Is it even possible to have match expressions inside other match expressions like this? And what would be the correct way to end the inner match so I can continue matching the other possibilities?</p>
  
  <p>Ignore the logic, since it's pretty much what I came up with first, it's just that I haven't been able to try it since I have to deal with this "match" error first, although any recommendation on how to handle the recursiveness or the logic would be welcome.</p>