Skip to content

Instantly share code, notes, and snippets.

@gkthiruvathukal
Created March 17, 2015 17:59
Show Gist options
  • Select an option

  • Save gkthiruvathukal/950fdeddafe1a68f5fb1 to your computer and use it in GitHub Desktop.

Select an option

Save gkthiruvathukal/950fdeddafe1a68f5fb1 to your computer and use it in GitHub Desktop.
Getting inline abs() to work in Scala with sealed class + @inline
import scala.util._
sealed class Abs {
@inline def abs(x : Int) : Int = if (x < 0) -x else x
}
object gcd {
val c = new Abs
def euclid(x: Int, y: Int): Int = {
if (x == 0) y
else if (x < 0) euclid(c.abs(x), y)
else if (y < 0) euclid(x, c.abs(y))
else euclid(y % x, x)
}
def main(args: Array[String]) {
val a = Try(args(0).toInt).getOrElse(0)
val b = Try(args(1).toInt).getOrElse(1)
val gcd = euclid(a, b)
println(s"euclid($a, $b) = $gcd")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment