fix exponential-growth bug in pattern matching implementation