加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala中写出毕达哥拉斯定理?

发布时间:2020-12-16 09:47:25 所属栏目:安全 来源:网络整理
导读: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)。 问题是,你将如何定义这样的函数在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)。

问题是,你将如何定义这样的函数在Scala中,它可以使用任何类型实现适当的方法?

对于上下文,想象一下你想要使用Int,Double,Int-Rational,Double-Rational,BigInt或BigInt-Rational类型的数学定理的整个库,这取决于你在做什么,以及速度,精度,准确性和范围要求。

解决方法

这只适用于Scala 2.8,但它工作:

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,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

更一般来说,trait Numeric是如何解决这类问题的有效参考。参见排序。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读