【问题标题】:Scala - "not found: value" when calling a function before defining itScala - 在定义函数之前调用函数时出现“未找到:值”
【发布时间】:2021-02-26 10:34:56
【问题描述】:

我是 Scala 新手,开始学习 Coursera 课程。

在第一节课中,有一个练习尝试使用牛顿法计算数字的平方根。

这是来自 scala 工作表的解决方案:

def abs(x: Double) = if (x < 0) -x else x

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(8)

评估此工作表会返回此错误:

not found: value isGoodEnough

但是,将函数定义移到工作表顶部后,一切似乎都运行良好:

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(8)

问题在于课程讲师能够毫无问题地执行第一段代码(调用后带有定义)。我什至可以在 https://scastie.scala-lang.org/ 上运行它,没有任何问题。

这是我的本地环境、版本或 IntelliJ 配置的问题吗?

【问题讨论】:

标签: scala


【解决方案1】:

答案:将运行类型从 REPL 更改为普通就可以了。 根据https://stackoverflow.com/a/62636337/15289443

普通评估模型在评估表达式之前一次性编译整个工作表,而 REPL 评估模型会在移动到下一个之前对每个表达式进行评估。

IntelliJ Scala 工作表已预先配置为使用 REPL 运行类型。

可以通过点击运行按钮旁边的“扳手”图标进行更改。

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多