我想在 2 的惰性串列中找到達到固定閾值(例如 10)的位置,例如:
LazyList.
continually(2).
zipWithIndex.
scanLeft((0,0)){case (acc, el) => (acc._1 el._1, el._2)}.
takeWhile(_._1 <= 10)
res72: LazyList[(Int, Int)] = LazyList(
(0, 0),
(2, 0),
(4, 1),
(6, 2),
(8, 3),
(10, 4)
)
是否可以在不收集所有中間結果的情況下以功能方式執行相同操作,僅在達到累積總和時回傳最終位置,foldLeft例如或類似?
uj5u.com熱心網友回復:
是的,你可以使用collectFirst,我也會在zipWithIndex之后移動scanLeft
LazyList
.continually(2)
.scanLeft(0)((acc, x) => acc x)
.zipWithIndex
.collectFirst {
case (x, idx) if (x >= 10) => idx
}
這會回傳一個,Option[Int]因為它collect可能永遠不會匹配,但你知道在這種情況下它會匹配,所以你可以.get或者.getOrElse(new IllegalStateException("This should have never happened"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/483489.html
標籤:斯卡拉
