Skip to content

Commit

Permalink
use the performance trick from traverseOnce
Browse files Browse the repository at this point in the history
  • Loading branch information
kailuowang committed Nov 20, 2017
1 parent f3805b5 commit 0ee9906
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions core/src/main/scala/cats/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,15 @@ import simulacrum.typeclass
case Right(_) => None
}

def collectFirst[A, B](fa: F[A])(pf: PartialFunction[A, B]): Option[B] =
def collectFirst[A, B](fa: F[A])(pf: PartialFunction[A, B]): Option[B] = {
//trick from TravsersableOnce
val sentinel: Function1[A, Any] = new scala.runtime.AbstractFunction1[A, Any]{ def apply(a: A) = this }
foldRight(fa, Eval.now(Option.empty[B])) { (a, lb) =>
if (pf.isDefinedAt(a)) Eval.now(Some(pf.apply(a))) else lb
val x = pf.applyOrElse(a, sentinel)
if (x.asInstanceOf[AnyRef] ne sentinel) Eval.now(Some(x.asInstanceOf[B]))
else lb
}.value
}

/**
* Like `collectFirst` from `scala.collection.Traversable` but takes `A => Option[B]`
Expand Down

0 comments on commit 0ee9906

Please sign in to comment.