Automatic flattening of sums and products during expression building