我有一个选项列表,我想不跳过任何值并返回第一个。
val list = List(None, None, None, Some(3));
list.dropWhile(!_.exists).take(1) // return 3
实际上是这样的:
val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.dropWhile(!solve(_).isDefined).take(1) // returns the result of solve method
我需要为每个None结果调用一次solve
函数,为最后一个Some结果调用一次。
答案 0 :(得分:1)
val list = List(None, None, None, Some(3));
list.flatten.headOption
回答第二个问题:
val list = List(1, 2, 3, 4)
def solve(value: Int): Option[Int] = ???
list.toStream.flatMap(solve).headOption // or call .head if you know what you're doing
答案 1 :(得分:0)
像这样:
def solve(hand: Hand): HandValue = all.foldLeft[Option[HandValue]](None) {
case (None, solver) => solver.solve(hand)
case (Some(value), _) => Some(value)
} get
答案 2 :(得分:0)
def takeFirst[T](list : List[Option[T]]): Option[T] = list.find(_.isDefined).flatten