refactoring (use foldLeft)