1

I'm new to Scala and started by following the Coursera course.

In the first session, there is an exercise that tries to calculate the square root of a number using the Newton method.

Here's the solution from a scala worksheet:

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)

Evaluating this worksheet returns this error:

not found: value isGoodEnough

However, after moving the function definitions to the top of the worksheet, everything seems to be working fine:

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)

The problem is that the course instructor is able to execute the first piece of code (with definitions after calling) with no issues. I have even been able to run this on https://scastie.scala-lang.org/ with no issues.

Is this a problem with my local environment, version, or my IntelliJ configurations?

Nikunj Kakadiya
  • 2,689
  • 2
  • 20
  • 35
reroo
  • 51
  • 6
  • Does this answer your question? [Calling functions before they are defined (forward reference extends over definition of variable)](https://stackoverflow.com/questions/22108579/calling-functions-before-they-are-defined-forward-reference-extends-over-defini) – AlleXyS Feb 26 '21 at 10:47
  • @AlleXyS I don't think so. Can you explain in more detail? – Thilo Feb 26 '21 at 12:44

1 Answers1

4

Answer: Changing the Run Type from REPL to Plain did the trick. According to https://stackoverflow.com/a/62636337/15289443

Plain evaluation model compiles the whole worksheet in one go before evaluating expressions, whilst REPL evaluation model evaluates each expression on the go before moving to the next one.

The IntelliJ Scala worksheet is preconfigured to use the REPL run type.

It can be changed by clicking the "wrench" icon next to the run button.

reroo
  • 51
  • 6