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

remove some casts in AndThen #3518

Merged
merged 1 commit into from
Jul 13, 2020
Merged
Changes from all commits
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
43 changes: 16 additions & 27 deletions core/src/main/scala/cats/data/AndThen.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package data

import java.io.Serializable
import cats.arrow.{ArrowChoice, CommutativeArrow}
import scala.annotation.tailrec

/**
* A function type of a single input that can do function composition
Expand Down Expand Up @@ -87,25 +88,19 @@ sealed abstract class AndThen[-T, +R] extends (T => R) with Product with Seriali
}

private def runLoop(start: T): R = {
var self: AndThen[Any, Any] = this.asInstanceOf[AndThen[Any, Any]]
var current: Any = start.asInstanceOf[Any]
var continue = true

while (continue) {
@tailrec
def loop[A, B](self: AndThen[A, B], current: A): B =
self match {
case Single(f, _) =>
current = f(current)
continue = false
case Single(f, _) => f(current)

case Concat(Single(f, _), right) =>
current = f(current)
self = right.asInstanceOf[AndThen[Any, Any]]
loop(right, f(current))

case Concat(left @ Concat(_, _), right) =>
self = left.rotateAccum(right)
loop(left.rotateAccum(right), current)
}
}
current.asInstanceOf[R]

loop(this, start)
}

final private def andThenF[X](right: AndThen[R, X]): AndThen[T, X] =
Expand All @@ -115,21 +110,15 @@ sealed abstract class AndThen[-T, +R] extends (T => R) with Product with Seriali

// converts left-leaning to right-leaning
final protected def rotateAccum[E](_right: AndThen[R, E]): AndThen[T, E] = {
var self: AndThen[Any, Any] = this.asInstanceOf[AndThen[Any, Any]]
var right: AndThen[Any, Any] = _right.asInstanceOf[AndThen[Any, Any]]
var continue = true
while (continue) {
self match {
case Concat(left, inner) =>
self = left.asInstanceOf[AndThen[Any, Any]]
right = inner.asInstanceOf[AndThen[Any, Any]].andThenF(right)

case _ => // Single
self = self.andThenF(right)
continue = false
@tailrec
def loop[A, B, C](left: AndThen[A, B], right: AndThen[B, C]): AndThen[A, C] =
left match {
case Concat(left1, right1) =>
loop(left1, Concat(right1, right))
case notConcat => Concat(notConcat, right)
}
}
self.asInstanceOf[AndThen[T, E]]

loop(this, _right)
}

override def toString: String =
Expand Down