sant016
sant016

Reputation: 345

Take the element in a list that satisfy a condition

I have a List[Either[Error, Satisfaction]], and I need to take the first element in that list that isRight. If there are no elements that satisfy isRight, then I should return the last Error.

For now I've thought on a takeWhile(_.isLeft), find the size of this last list, and then get the nth element in the original list, with n being the size of the first-lefts list, but I think there's a better solution for this.

Any help will be strongly appreciated.

Upvotes: 0

Views: 629

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

You can do this, which has the dual problem to @jwvh's answer: if rest is empty, it has to go over the list again.

val (lefts, rest) = list.span(_.isLeft)
rest.headOption.getOrElse(lefts.last) 
// or orElse(lefts.lastOption) if list can be empty

And the recursive solution without either problem for completeness (assuming non-empty list):

def foo(list: List[Either[Error, Satisfaction]]) = list match {
  case x :: tail => if (x.isRight || tail.isEmpty) x else foo(tail)
}

Not that much more code.

Upvotes: 2

jwvh
jwvh

Reputation: 51271

You might reduce the list like so:

lst.reduceLeft((a,b) => if (a.isRight) a else b)

The result will be the first Right element or, if there is none, the final Left element.

Upvotes: 3

Related Questions