Skip to content

Commit

Permalink
Replace traverse1 with more performant implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Luka Jacobowitz committed May 28, 2017
1 parent 17d8d62 commit 0591bf8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
11 changes: 7 additions & 4 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -354,10 +354,13 @@ private[data] sealed trait NonEmptyListInstances extends NonEmptyListInstances0

def extract[A](fa: NonEmptyList[A]): A = fa.head

def traverse1[G[_] : Apply, A, B](as: NonEmptyList[A])(f: A => G[B]): G[NonEmptyList[B]] = {
as.map(a => Apply[G].map(f(a))(NonEmptyList.of(_)))
.reduceLeft((acc, a) => (acc |@| a).map( _ |+| _ ))
}
def traverse1[G[_], A, B](nel: NonEmptyList[A])(f: A => G[B])(implicit G: Apply[G]): G[NonEmptyList[B]] =
Foldable[List].reduceRightToOption[A, G[List[B]]](nel.tail)(a => G.map(f(a))(_ :: Nil)) { (a, lglb) =>
G.map2Eval(f(a), lglb)(_ :: _)
}.map {
case None => G.map(f(nel.head))(NonEmptyList(_, Nil))
case Some(gtail) => G.map2(f(nel.head), gtail)(NonEmptyList(_, _))
}.value

override def traverse[G[_], A, B](fa: NonEmptyList[A])(f: A => G[B])(implicit G: Applicative[G]): G[NonEmptyList[B]] =
fa traverse f
Expand Down
11 changes: 7 additions & 4 deletions core/src/main/scala/cats/data/NonEmptyVector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,13 @@ private[data] sealed trait NonEmptyVectorInstances {

def extract[A](fa: NonEmptyVector[A]): A = fa.head

def traverse1[G[_] : Apply, A, B](as: NonEmptyVector[A])(f: A => G[B]): G[NonEmptyVector[B]] = {
as.map(a => Apply[G].map(f(a))(NonEmptyVector.of(_)))
.reduceLeft((acc, a) => (acc |@| a).map( _ |+| _ ))
}
def traverse1[G[_], A, B](nel: NonEmptyVector[A])(f: A => G[B])(implicit G: Apply[G]): G[NonEmptyVector[B]] =
Foldable[Vector].reduceRightToOption[A, G[Vector[B]]](nel.tail)(a => G.map(f(a))(_ +: Vector.empty)) { (a, lglb) =>
G.map2Eval(f(a), lglb)(_ +: _)
}.map {
case None => G.map(f(nel.head))(NonEmptyVector(_, Vector.empty))
case Some(gtail) => G.map2(f(nel.head), gtail)(NonEmptyVector(_, _))
}.value

override def foldLeft[A, B](fa: NonEmptyVector[A], b: B)(f: (B, A) => B): B =
fa.foldLeft(b)(f)
Expand Down

0 comments on commit 0591bf8

Please sign in to comment.