Created
March 17, 2015 17:59
-
-
Save gkthiruvathukal/950fdeddafe1a68f5fb1 to your computer and use it in GitHub Desktop.
Getting inline abs() to work in Scala with sealed class + @inline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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