scala - 方法将给定函数两次应用于给定参数
问题描述
例如,如果给定Math.sqrt
和 2.0,它会计算Math.sqrt(Math.sqrt(2.0))
.
使用功能:
def applyTwice[A](f: A => A, argument: A) = ???
然后测试上面的例子
解决方案
如果我正确理解了您的问题,您希望将函数两次应用于参数并对其进行测试。
例如,如果您需要对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
推荐阅读
- django - 在 CreateView 表单中显示 django unique_together 的错误
- sql-server - SQL Server:JSON - 按数组内数组中的值过滤
- jquery - 更新到 JQuery 3.6.0,Jquery UI 出现 JQMigrate 错误
- c# - Xamarin.iOS CollectionView - 添加新元素会导致整个列表被刷新
- arrays - 如何将数组的值分配给范围?
- ios - 使用 Itext 7.1.14 无法在 iPhone 上的 SVG 中定位文本
- python - 根据字符串计算df中的行
- numpy - 从 .VTU 文件访问和操作 Ccell 数据
- machine-learning - 假设在 Pytorch 中调用 torch.distributed.destroy_process_group() 在哪里?
- reactjs - React App 只为 App.js 中的某些路由包装高阶组件