How does one write the Pythagoras Theorem in Scala?

后端 未结 4 1464
时光取名叫无心
时光取名叫无心 2020-12-03 01:27

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 Theore

4条回答
  •  情话喂你
    2020-12-03 01:58

    Some thoughts on Daniel's answer:

    I've experimented to generalize Numeric to Real, which would be more appropriate for this function to provide the sqrt function. This would result in:

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

    It is tricky, but possible, to use literal numbers in such generic functions.

    def pythagoras[T](a: T, b: T)(sqrt: (T => T))(implicit n: Numeric[T]) = {
       import n.mkNumericOps
       implicit val fromInt = n.fromInt _
    
       //1 * sqrt(a*a + b*b)   Not Possible!
       sqrt(a*a + b*b) * 1    // Possible
    }
    

    Type inference works better if the sqrt is passed in a second parameter list.

    Parameters a and b would be passed as Objects, but @specialized could fix this. Unfortuantely there will still be some overhead in the math operations.

    You can almost do without the import of mkNumericOps. I got frustratringly close!

提交回复
热议问题