如何在 Scala 中编写毕达哥拉斯定理? [英] How does one write the Pythagoras Theorem in Scala?

查看:53
本文介绍了如何在 Scala 中编写毕达哥拉斯定理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直角三角形斜边的平方等于另外两条边的平方和.

The square of the hypotenuse of a right triangle is equal to the sum of the squares on the other two sides.

这是毕达哥拉斯定理.根据边的长度a"和b"计算斜边的函数将返回 sqrt(a * a + b * b).

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).

问题是,您将如何在 Scala 中定义这样一个函数,使其可以与实现适当方法的任何类型一起使用?

对于上下文,想象一个完整的数学定理库,您想根据您的操作以及速度、精度、准确度,将其与 Int、Double、Int-Rational、Double-Rational、BigInt 或 BigInt-Rational 类型一起使用和范围要求.

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.

推荐答案

这仅适用于 Scala 2.8,但确实有效:

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

更一般地说,特征 Numeric 是如何解决此类问题的有效参考.另请参阅订购.

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

这篇关于如何在 Scala 中编写毕达哥拉斯定理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆