I am new to Scala and functional programming.
I was solving problem where you have to read number, and then that number of integers. After that you should calculate sum of all digits in all the integers.
Here is my code
def sumDigits(line: String) =
line.foldLeft(0)(_ + _.toInt - '0'.toInt)
def main(args: Array[String]) {
val numberOfLines = Console.readInt
val lines = for (i <- 1 to numberOfLines) yield Console.readLine
println(lines.foldLeft(0)( _ + sumDigits(_)))
}
Is there more elegant or efficient way?
sumDigits()can be implemented easier withsum:Second
foldLeft()can also be replaced withsum:Which brings us to the final version (notice there is no
main, instead with extendApp):Or if you really want to squeeze as much as possible in one line, inline
sumDigits(not recommended):