Skip to content

Instantly share code, notes, and snippets.

@sammyrulez
Created September 18, 2015 13:47
Show Gist options
  • Save sammyrulez/1bfcd9dbfb315c57762e to your computer and use it in GitHub Desktop.
Save sammyrulez/1bfcd9dbfb315c57762e to your computer and use it in GitHub Desktop.
/**
* Created by sam on 17/09/15.
*/
object PrimaEsercitazione {
def main(args: Array[String]) {
println("Distance test:")
val point1: (Double, Double) = (1d, 2d)
val point2: (Double, Double) = (2d, 2d)
val distance: Double = PointDistance.eval(point1, point2)
println(s"Distance $point1 to $point2 = $distance")
println("\n Equation test:")
val verticalEq = LineEquation((1d,2d),(1d,4d))
println(verticalEq)
val defaultEq = LineEquation((1d,1d),(2d,2d))
println(defaultEq)
val defFunct: (Double) => Double = defaultEq.asFunction()
println("\n Inclusion test: ")
val isIn = defFunct(3d).equals(3d)
println("(3,3) is in? " + isIn)
val notIn = defFunct(4d).equals(3d)
println("(4,3) is in? " + notIn)
}
}
object PointDistance {
def eval(point1: Tuple2[Double,Double],point2: Tuple2[Double,Double]) = {
Math.sqrt(Math.pow(point1._1 - point2._1, 2) + Math.pow(point1._2 - point2._2, 2) )
}
}
object LineEquation{
def apply(a:Double,b:Double): LineEquation ={
new LineEquation(a,b)
}
def apply(point1: Tuple2[Double,Double],point2: Tuple2[Double,Double]): LineEquation ={
val y = point2._2 - point1._2
val x = point2._1 - point1._1
val a = y / x
point1._1 - point2._1 match {
case 0d => new LineEquation(0,point1._1)
case _ => new LineEquation(a,point2._2 - a* point2._1)
}
}
}
class LineEquation(val a:Double,val b:Double){
override def toString: String = s" y = $a * x + $b"
def asFunction():Double => Double = { x:Double => x * a + b }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment