SCALA: Use functional programming instead of loop