Created
June 11, 2014 05:40
-
-
Save TheEmpty/19992dbc74fc399ee6da to your computer and use it in GitHub Desktop.
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
| class Point { | |
| var x : Int = 0 | |
| var y : Int = 0 | |
| def apply(newX : Int, newY : Int) : Point = { | |
| x = newX | |
| y = newY | |
| this | |
| } | |
| def +(operand : Point) : Point = { | |
| Point(x + operand.x, y + operand.y) | |
| } | |
| def -(operand : Point) : Point = { | |
| Point(x - operand.x, y - operand.y) | |
| } | |
| def Δ(operand : Point) : Point = { | |
| this delta operand | |
| } | |
| def delta(operand : Point) : Point = { | |
| val mx = Math.max(x - operand.x, operand.x - x) | |
| val my = Math.max(y - operand.y, operand.y - y) | |
| Point(mx, my) | |
| } | |
| def >=<(operand : Point) : Point = { | |
| this midpoint operand | |
| } | |
| def midpoint(operand : Point) : Point = { | |
| val mx = (x + operand.x) / 2 | |
| val my = (y + operand.y) / 2 | |
| Point(mx, my) | |
| } | |
| override def toString() : String = { | |
| "[%,d, %,d]".format(x,y) | |
| } | |
| override def equals(obj : Any) : Boolean = { | |
| if (obj.isInstanceOf[Point]) { | |
| val ob = obj.asInstanceOf[Point] | |
| ob.x == this.x && ob.y == this.y | |
| } else { | |
| false | |
| } | |
| } | |
| override def hashCode() : Int = { | |
| x * 5 + y * 3 | |
| } | |
| } | |
| // Static methods, instead of saying new Point(x, y) just Point(x, y) | |
| object Point { | |
| def apply(x : Int, y : Int) : Point = { | |
| val p = new Point | |
| p(x, y) | |
| } | |
| } | |
| object Driver { | |
| def main(args : Array[String]) = { | |
| val p1 = Point(5, 3) | |
| println(p1) | |
| val p2 = Point(1, 1) | |
| println(p2) | |
| printf("%s Δ %s = %s%n", p1, p2, p1 Δ p2) | |
| printf("%s and %s have a midpoint of %s%n", p1, p2, p1 >=< p2) | |
| printf("%s == %s => %b%n", p1, p2, p1 == p2) | |
| printf("%s Δ %s == %s Δ %s => %b%n", p1, p2, p2, p1, (p2 Δ p1) == (p1 Δ p2)) | |
| } | |
| } | |
| /* | |
| OUTPUT: | |
| [5, 3] | |
| [1, 1] | |
| [5, 3] Δ [1, 1] = [4, 2] | |
| [5, 3] and [1, 1] have a midpoint of [3, 2] | |
| [5, 3] == [1, 1] => false | |
| [5, 3] Δ [1, 1] == [1, 1] Δ [5, 3] => true | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment