0

I am trying to understand the meaning of "evaluation".

I am learning about call by name and call by value in Scala and I am confused about what evaluation means. Is it something that compiler performs to understand my code or is it something like executing/verifying of a method before the actual call to the method ?

I couldn't find a clear explanation except for evaluation strategies.

Could you explain the evaluation for the following example ?

 def callByValue(x : Unit) = {
    for (i <- 0 until 5) {
      print(x)
    }
  }

  def callByName(x : => Unit) = {
    for (i <- 0 until 5) {
      print(x)
    }
  }
eaayoata
  • 5
  • 1
  • 4

2 Answers2

1

Let's consider an even simpler example.

def callByValue(x : Unit)   = if (1 > 0) () else x
def callByName(x : => Unit) = if (1 > 0) () else x

Notice that 1 > 0 is, of course, always true so neither of these methods can ever return the x value.

Now let's call them.

callByValue(println("Value"))  // res0: Unit = ()
callByName(println("Name"))    // res1: Unit = ()

Both calls return (), which is the only value of type Unit, but the first one, callByValue(), has a side effect. It prints the word "Value" to STDOUT. The word "Name" is not printed. Why is that?

It's because the argument passed to callByValue() is evaluated (i.e. executed) when the method is called. The argument to callByName() is not evaluated until that argument, x, is referenced, but it is never referenced because the if condition is always true, the else clause is never executed, and x is never evaluated.

jwvh
  • 50,871
  • 7
  • 38
  • 64
0

.. the meaning of "evaluation" ... Is it something that compiler performs to understand my code or is it something like executing/verifying of a method before the actual call to the method ?

There are many good examples that exemplify the difference between the evaluation strategies, e.g. the one given by @jwvh. There is also a wikipedia article on this subject.

It seems to me that you are confused by the word "evaluation". Perhaps it is easier if you consider an interpreter instead of a compiler. The interpreter is executing your program, also known as evaluating. For instance Python comes with a builtin function eval (and also "exec" btw).

"Evaluation strategy" means when or how the interpreter is going to execute/evaluate the code that will return the actual parameter value.

For a compiled program this is the same except the compiler makes this decision (actually the programmer made it when defining the function) when generating the executable code.

esl
  • 245
  • 1
  • 9