Well... first of all... I think you should call your function collect
and not sum
. Now, lets help you write this collect
.
So... your collect
function takes two arguments,
1 - A collector
function.
2 - Things to accumulate.
So... your collector function needs to know two things... first is already collected
and second is next item to collect... and it will produce the next collected.
Which means that for collection of Int
, your collector
function will have a signature (Int, Int) => Int
.
So, your collect function should have following signature,
def collect(collector: (Int, Int) => Int)(items: Int*): Int = ???
Now... lets come to implement it.
1 - Using reduce
def collect(collector: (Int, Int) => Int)(items: Int*): Int =
items.reduce(collector)
2 - Using fold
def collect(collector: (Int, Int) => Int)(items: Int*): Int =
items.fold(0)(collector)
Now, you can use it like this,
val l = List(1,2,3,4,5,6,7,8,9)
val b = collect((i1, i2) => i1 + i2)(l: _*)