Reducing options in scala?
Asked Answered
S

1

6

What is the best way to do this:

def reduce[A](x: Option[A], y: Option[A])(f: (A, A) => A): Option[A] = 
  (x, y) match {
    case (Some(a), Some(b)) => Some(f(a, b))
    case (None, None) => None
    case (_,  None) => x
    case (None, _) => y
  }

I looked at this question but his case is slightly different from mine...

Shoa answered 7/4, 2014 at 2:13 Comment(0)
I
14

The shortest is probably

(x ++ y).reduceLeftOption(f)

which works because of an implicit conversion from Option to Iterable which happens to have a method that does exactly what you need.

Instruct answered 7/4, 2014 at 2:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.