Skip to content

Partial Function: Prevent double evaluation of pattern matchers and guards #4177

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

Closed
allanrenucci opened this issue Mar 25, 2018 · 1 comment

Comments

@allanrenucci
Copy link
Contributor

allanrenucci commented Mar 25, 2018

The documentation of PartialFunction::applyOrElse says:

For all partial function literals the compiler generates an applyOrElse implementation which avoids double evaluation of pattern matchers and guards.

However this is not currently the case in Dotty:

object Test {
  private[this] var count = 0

  def test(x: Int) = { count += 1; true }

  object Foo {
    def unapply(x: Int): Option[Int] = { count += 1; Some(x) }
  }

  def main(args: Array[String]): Unit = {
    val res = List(1, 2).collect { case x if test(x) => x }
    println(count) // prints 4 but should be 2

    count = 0
    val res2 = List(1, 2).collect { case Foo(x) => x }
    println(count) // prints 4 but should be 2
  }
}
@allanrenucci
Copy link
Contributor Author

allanrenucci commented Mar 26, 2018

Needed to make collections-strawman tests pass

allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 4, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 5, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 5, 2018
@biboudis biboudis assigned allanrenucci and unassigned biboudis Apr 6, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 11, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 11, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 12, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 12, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 17, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 17, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 20, 2018
allanrenucci added a commit to dotty-staging/dotty that referenced this issue Apr 25, 2018
odersky added a commit that referenced this issue Apr 27, 2018
Fix #4177: Generate optimised applyOrElse implementation for partial function literals
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants