19

我最近在 scala 并试图通过一些简单的 scala 工作表。

IDE 是 Intellij IDEA 社区版和操作系统 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)

有什么建议么?

4

3 回答 3

21

完整的错误信息是error: not found: value abs。找不到值“abs”。你想要math.abs。或者,您可以import math._在需要这些数学函数之前添加某个位置。

于 2013-08-18T14:25:31.570 回答
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
于 2015-04-09T17:30:04.183 回答
1

还有一些没有冗余代码的最简单方法:

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)
}
于 2013-08-18T15:07:22.980 回答