When writing an answer to another question here, I came across the problem of producing lists of integers having a certain total and only consisting of a certain number and an optional rest. So for total 21 and number 5 you would get List(5, 5, 5, 5, 1)
.
Solving the problem is obviously not hard. However, I have the feeling that it can be written more concisely than this:
def uniformList(sum: Int, num: Int): List[Int] = {
val rest = sum % num
List.fill(sum / num)(num) ::: (if (rest == 0) Nil else List(rest))
}
Of course I could inline the rest
but I don't think it makes it more readable. I'm not looking for a performant solution but a more concise one. My feeling is that there should be a solution that is as easy to grasp as the concrete example I gave in the first paragraph.