I have a function $F$ taking arbitrarily many arguments from ${a,c,z}$ where practically (technically it isn't) $a$ works as an opening bracket and $z$ as a closing. ($c$ stands for a value.) Double brackets around a value shall cancel, but if I write F[v___,a,a,x___,z,z,w___]:=F[v,x,w] it obviously flies me in the face since e.g. in F[a,A,c,z,a,c,Z,z] the marked $Z$ does not close the marked $A$. Clearly $F[c,z,a,c]$ is syntax nonsense, but unfortunately, just counting brackets (e.g. by M[F[x___]]:=F[x]/.{a->1,c->0,z->-1,F->Plus}; ) is not enough to recognize this. I need a "Catalan Counter": if at any point the partial sum of $M$ is $<0$, the rule may not apply. I surely could hack this together in half an hour, but speed might be relevant. So, anyone can come up with an elegant solution F[v___,a,a,x___,z,z,w___]:=F[v,x,w]/;Br[x] where $Br$ returns true iff $x$ is correctly bracket-matched?
(EDIT: M[F[x___]] := F[x] /. {a -> 1, c -> 0, z -> -1, F -> List} // Accumulate // Min; - is that a good idea? If it returns $<0$, I'd say the brackets don't match.)
Additional headscratcher: M[x___]:=x/.{a->1,c->0,z->-1,Sequence->Plus}; would be more elegant...but doesn't work. Why doesn't the pattern matcher recognize $x$ as a sequence? Can I somehow "guide" it?
FullForm[x___]isPattern[x,BlankNullSequence[]]notSequence$\endgroup$