Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding instances for ArraySeq #3273

Merged
merged 6 commits into from
Jan 29, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Implementing tailRecM
  • Loading branch information
BalmungSan committed Jan 28, 2020
commit 194d334c53896fb6c1f4f9a7bd0a63ccb1483f6f
29 changes: 26 additions & 3 deletions core/src/main/scala-2.13+/cats/instances/arraySeq.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cats
package instances

import scala.annotation.tailrec
import scala.collection.immutable.ArraySeq

trait ArraySeqInstances extends cats.kernel.instances.ArraySeqInstances {
Expand Down Expand Up @@ -72,8 +73,30 @@ object ArraySeqInstances {
override def zipWithIndex[A](fa: ArraySeq[A]): ArraySeq[(A, Int)] =
fa.zipWithIndex

def tailRecM[A, B](a: A)(fn: A => ArraySeq[Either[A, B]]): ArraySeq[B] =
???
def tailRecM[A, B](a: A)(fn: A => ArraySeq[Either[A, B]]): ArraySeq[B] = {
val buf = ArraySeq.untagged.newBuilder[B]

@tailrec
def loop(state: List[Iterator[Either[A, B]]]): Unit =
state match {
case h :: tail if h.isEmpty =>
loop(state = tail)
case h :: tail =>
h.next match {
case Right(b) =>
buf += b
loop(state)
case Left(a) =>
loop(state = fn(a).iterator :: h :: tail)
}

case Nil => ()
}

loop(state = fn(a).iterator :: Nil)

buf.result()
}

override def exists[A](fa: ArraySeq[A])(p: A => Boolean): Boolean =
fa.exists(p)
Expand All @@ -82,7 +105,7 @@ object ArraySeqInstances {
fa.forall(p)

override def get[A](fa: ArraySeq[A])(idx: Long): Option[A] =
if (idx < fa.length && idx.isValidInt) Some(fa(idx.toInt)) else None
if (idx >= 0 && idx < fa.length && idx.isValidInt) Some(fa(idx.toInt)) else None

override def isEmpty[A](fa: ArraySeq[A]): Boolean =
fa.isEmpty
Expand Down