Counting functions and formal series in noncommuting variables