我刚刚在scala上尝试传递一些简单的scala工作表。
IDE是Intellij IDEA社区版和OS Ubuntu 12.04,sbt
已正确安装。
但它会引发错误 - error: not found: value
OI无法理解为什么会发生这种情况:
的代码: 的
object session {
1 + 2
def abs(x: Double) = if (x < 0) -x else x <== update this line
def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) < 0.001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrt(x: Double) = sqrtIter(1.0, x)
sqrt(2)
sqrt(4)
}
从屏幕右侧输出:
> res0: Int = 3
> <console>:8: error: not found: value isGoodEnough
if (isGoodEnough(guess, x)) guess else sqrtIter(improve(guess, x), x)
^
<console>:8: error: not found: value improve
if (isGoodEnough(guess, x)) guess else sqrtIter(improve(guess, x), x)
^
> <console>:8: error: not found: value abs
abs(guess * guess - x) < 0.001
^
> improve: (guess: Double, x: Double)Double
> <console>:7: error: not found: value sqrtIter
def sqrt(x: Double) = sqrtIter(1.0, x)
^
> <console>:8: error: not found: value sqrt
sqrt(2)
^
> <console>:8: error: not found: value sqrt
sqrt(4)
有什么建议吗?
答案 0 :(得分:20)
完整的错误消息为error: not found: value abs
。找不到值“abs”。你想要math.abs
。或者,您可以在需要这些数学函数之前在某处添加import math._
。
答案 1 :(得分:3)
我和你有同样的问题。我不认为导入math.abs或导入math._是有效的,因为在代码中定义了abs。
对我有用的是重新组织函数定义的顺序。在下面使用它之前,您必须先定义上述内容。
object session {
def abs(x: Double) = if (x<0) - x else x
def isGoodEnough(guess: Double, x: Double) =
abs(guess * guess - x) < 0.001
def improve(guess: Double, x: Double) =
(guess + x / guess) / 2
def sqrtIter(guess: Double, x: Double): Double =
if(isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
def sqrt(x: Double) = { sqrtIter(1.0, x) }
sqrt(2)
sqrt(4)
}
返回:
> abs: (x: Double)Double
> isGoodEnough: (guess: Double, x: Double)Boolean
> improve: (guess: Double, x: Double)Double
> sqrtIter: (guess: Double, x: Double)Double
> sqrt: (x: Double)Double
> res0: Double = 1.4142156862745097
> res1: Double = 2.0000000929222947
答案 2 :(得分:0)
没有多余代码的最简单方法:
object session {
1 + 2
def abs(x: Double) = if (x < 0) -x else x
def sqrt(x: Double) = {
def sqrtIter(guess: Double): Double =
if (isGoodEnough(guess)) guess
else sqrtIter(improve(guess))
def isGoodEnough(guess: Double) =
abs(guess * guess - x) / x < 0.001
def improve(guess: Double) =
(guess + x / guess) / 2
sqrtIter(1.0)
}
sqrt(2)
sqrt(4)
sqrt(1e-16)
sqrt(1e60)
}