首页 > 解决方案 > 方法将给定函数两次应用于给定参数

问题描述

例如,如果给定Math.sqrt和 2.0,它会计算Math.sqrt(Math.sqrt(2.0)).

使用功能:

def applyTwice[A](f: A => A, argument: A) = ???

然后测试上面的例子

标签: scala

解决方案


如果我正确理解了您的问题,您希望将函数两次应用于参数并对其进行测试。

例如,如果您需要对Math.sqrt一个参数应用两次,您可以通过以下代码实现:

val sqrt: Double => Double = Math.sqrt
def applyTwice[A](f: A => A, d: A) = {
  f(f(d))
}

println(applyTwice[Double](sqrt, 625))

assert(applyTwice[Double](sqrt, 625) == 5.0) // will check if applyTwice return 5.0

推荐阅读