-7

I am trying to get the sum of arguments using currying in Scala. This is a very basic question so please don't go hard on it.

If you can answer the question then please otherwise let it be:

  object MultiSum extends App {

      var res=0

         def sum(f:Int=>Int)(x:Int*)={f(x)}

         val a=List(1,2,3,4,5,6,7,8,9)

         val b=sum(x=>x+x)(a:_*)
    }

So val b will be storing the result of all the numbers passed in the List in var a

Thanks.

Abhinav
  • 658
  • 1
  • 9
  • 27

1 Answers1

2

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: _*)
sarveshseri
  • 13,738
  • 28
  • 47