代码:
object Integral {
def approx(start: Double, end: Double, nIntervals: Int)(f: Double => Double): Double = {
val delta = (end - start) / nIntervals
val halfDelta = delta / 2
val xs = start until end by delta
xs.map(x => f(x + halfDelta) * delta).sum
}
def approx(startEnd: Array[Double], nIntervas: Int)(f: Double => Double): Double = {
require(startEnd.length == 2)
val startEndSorted = startEnd.sorted
val res = approx(startEndSorted(0), startEndSorted(1), nIntervas)(f)
if(startEndSorted == startEnd) res else (-res)
}
}
object IntegralTest {
def f1(x: Double) = {
math.pow(x, 3) - 6 * x
}
println(Integral.approx(0, 3, 6)(f1))
println(Integral.approx(0, 1, 60000)(f1))
def f2(x: Double) = {
math.sqrt(1 - x * x)
}
println(Integral.approx(0, 1, 60000)(f2))
println(math.Pi / 4)
println(Integral.approx(0, 3, 60000)({
(x: Double) => x - 1
}))
println(Integral.approx(1, 2, 5)({
(x: Double) => 1 / x
}))
// test the exponential function
println(Integral.approx(1, 3, 60000)(math.exp))
println(math.exp(3) - math.exp(1))
}
我想将approx(start: Double, end: Double, nIntervals: Int)(f: Double => Double): Double
设为私有,并将所有对它的引用更改为approx(startEnd: Array[Double], nIntervas: Int)(f: Double => Double): Double
,有没有办法在intellij中安全无忧地执行此操作?
我很快意识到,对于这个特定情况,我可以用更好的方式处理它(通过递归):
def approx(start: Double, end: Double, nIntervals: Int)(f: Double => Double): Double = {
if(start > end) {
-approx(end, start, nIntervals)(f)
} else {
val delta = (end - start) / nIntervals
val halfDelta = delta / 2
val xs = start until end by delta
xs.map(x => f(x + halfDelta) * delta).sum
}
}
但我仍然有兴趣了解如何重构旧的有问题的代码,因为它可能在将来有用。
答案 0 :(得分:-1)
我不知道你为Scala使用它的事实是否会改变任何东西,但你应该能够右键单击一个函数,并Change method signature
到你想要的那个(所以你不会&# 39; t用function2本身替换function1,而是修改f1以匹配f2)。
编辑:根据本评论,这不会起作用。无论如何,为了提及功能而离开。