How does one write the Pythagoras Theorem in Scala?

scala

Solution

This only works on Scala 2.8, but it does work:

scala> def pythagoras[T](a: T, b: T, sqrt: T => T)(implicit n: Numeric[T]) = {
     | import n.mkNumericOps
     | sqrt(a*a + b*b)
     | }
pythagoras: [T](a: T,b: T,sqrt: (T) => T)(implicit n: Numeric[T])T

scala> def intSqrt(n: Int) = Math.sqrt(n).toInt
intSqrt: (n: Int)Int

scala> pythagoras(3,4, intSqrt)
res0: Int = 5

More generally speaking, the trait `Numeric` is effectively a reference on how to solve this type of problem. See also `Ordering`.

Problem

The square of the hypotenuse of a right triangle is equal to the sum of the squares on the other two sides. This is Pythagoras's Theorem. A function to calculate the hypotenuse based on the length "a" and "b" of it's sides would return sqrt(a * a + b * b). The question is, how would you define such a function in Scala in such a way that it could be used with any type implementing the appropriate methods? For context, imagine a whole library of math theorems you want to use with Int, Double, Int-Rational, Double-Rational, BigInt or BigInt-Rational types depending on what you are doing, and the speed, precision, accuracy and range requirements.

Original source