Skip to content
This repository has been archived by the owner on Nov 29, 2020. It is now read-only.

Optimize Option[A] as A | Null #51

Open
sir-wabbit opened this issue Sep 4, 2018 · 1 comment
Open

Optimize Option[A] as A | Null #51

sir-wabbit opened this issue Sep 4, 2018 · 1 comment
Labels
optimization Code optimization opportunity.

Comments

@sir-wabbit
Copy link
Contributor

sir-wabbit commented Sep 4, 2018

As discussed with @Odomontois on Telegram, in non-polymorphic context, Option[A] can be replaced with A | Null (primitives would have to be replaced with their Java counterparts in Scala2).

Consider the following function, that computes the maximum value of all odd numbers in a list:

def maxOdd(l: List[Int]): Option[Int] = {
  def go(l: List[Int], sum: Option[Int]): Option[Int] = l match {
    case Nil => sum
    case x :: xs if x % 2 == 0 => go(xs, sum)
    case x :: xs => sum match {
      case None => go(xs, Some(x))
      case Some(y) => go(xs, Some(x max y))
    }
  }

  go(l, None)
}

We can optimize it as (Integer here plays the role of Int | Null):

def maxOdd(l: List[Int]): Option[Int] = {
  def go(l: List[Int], sum: Integer): Integer = l match {
    case Nil => sum
    case x :: xs if x % 2 == 0 => go(xs, sum)
    case x :: xs => sum match {
      case null => go(xs, x)
      case y => go(xs, x max y)
    }
  }

  Option(go(l, null))
}

This sort of rewriting should only be applied locally and to private functions.

@NeQuissimus
Copy link
Member

Just have to keep in mind that as soon as I do anything with the Option[A], this can go horribly wrong :)

Option(x).map(_ max y).getOrElse(y) is a little more difficult to re-write :)

@sir-wabbit sir-wabbit added the optimization Code optimization opportunity. label Sep 22, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
optimization Code optimization opportunity.
Projects
None yet
Development

No branches or pull requests

2 participants