joesan
joesan

Reputation: 15385

Scala recursive Case class reduction

I have a case class like this:

case class Test(i: Int, t: Option[Test])

I would now like to reduce this case class and add all the i's. So for example., if I have an input like this

val x = Test(1, Some(Test(2, Some(Test(3,None)))))

I expect the result to be 6 and here is what I have tried so far:

def all(acc: Int, test: Test): Int = { 
  if (test.t.isDefined) 
    all(acc, test.t.get)
  else 
    acc + test.i
}

This gives me 3 and I see that I'm missing a minor detail somewhere in the recursion and I'm not able to see where! Any clues?

Upvotes: 2

Views: 247

Answers (1)

meucaa
meucaa

Reputation: 1515

There you go:

def sum(acc: Int, test: Test): Int = {
  test.t match {
    case Some(x) => sum(acc + test.i, x)
    case None => acc + test.i
  }
}

And a version without accumulator:

def sum(test: Test): Int = {
  test.t match {
    case Some(x) => test.i + sum(x)
    case None => test.i
  }
}

Upvotes: 1

Related Questions