generalized and more efficient cat implementation