ktii
ktii

Reputation: 59

Scala - conditionally sum elements in list

I am trying to solve a beginner problem with lists but can't find an example to help me get it work. I am given a list of positive and negative integers (AccountHistory) and I need to check if the negative integers in this list have ever exceeded -1000. I expected my code to work with a freshly introduced helper function like this:

def checkAccount(account: AccountHistory): Boolean = {
def helper(i: AccountHistory): Int = {
  var total = 0
  i.collect{case x if x < 0 => Math.abs(x) + total}
  return total
}
if (helper(account) >1000) true else false
}

But it doesn't work. Please help me find my mistake or problem in wrong approach.

Edit: The pre-given tests include

assert(checkAccount(List(10,-5,20)))
assert(!checkAccount(List(-1000,-1)))

So if assert expects true then my approach is wrong to solve it like this.

By 'exceeded' I mean <-1000, for any or all elements in a list (like exceeding a credit amount in given period).

Upvotes: 0

Views: 741

Answers (2)

jwvh
jwvh

Reputation: 51271

I think this is what you're supposed to do:

def checkAccount(account: AccountHistory): Boolean = 
  account.forall(_ > -1000)

Upvotes: 2

chengpohi
chengpohi

Reputation: 14227

i.collect{case x if x < 0 => Math.abs(x) + total}

In the above code snippet, not assign back to total, maybe you need:

val total = i.filter(_ < 0).map(Math.abs).sum

Upvotes: 3

Related Questions