1

If the boolean operators &&, || are implemented as infix methods, then isn't short-circuit evaluation just a consequence of being implemented using call-by-name semantics, since, for example, the && method wouldn't then evaluate the second arg in any case if the first is false.

I'm just wondering because they are generally treated as separate topics (e.g in the Scala intro course I'm taking - https://class.coursera.org/progfun-003/lecture/5 ) but short-circuit evaluation seems to just be a consequence of call-by-name.

2 Answers 2

1

Turns out Martin answers the exact question 15 minutes later on in the same video! Yes, short-circuit evaluation is implemented using call by-name args. Martin discusses just this and defines the and function as follows:

  def and(x:Boolean, y: => Boolean) {
    if (x) y else false
  }

Note that if the second arg y was not call-by-name, then and(false,<infinite loop expr>) would not terminate, whereas we would expect it to return false due to short-circuit eval.

-1

I wouldn't say that it's a consequence. It is however a requirement.

5
  • 2
    It is a good thing someone posted an actual answer; yours is just an opinion. Imagine someone posting the opposite view, with just as little argumentation; which person would be correct? Dec 11, 2013 at 9:04
  • It's not an opinion, it's a fact. Why? Well because you can implement non-short-circuit evaluation with call-by-name semantics, but you cannot implement short-circuit evaluation without it. Hence that call-by-name semantics are a requirement. It is however not a consequence, since you still have your options open if call-by-name is used. This argumentation at least holds if you equate call-by-name with lazy evalutation, which I believe that the OP was doing. Dec 11, 2013 at 9:53
  • 3
    Then put that in your answer. Explain why. Don't just state it is so. Dec 11, 2013 at 9:54
  • @MartijnPieters fair enough. I suppose I could be a bit more clear. Wrote the answer on my cell, so was a bit too short I suppose. Dec 11, 2013 at 9:56
  • I commented because your post showed up in the low quality review queue (already downvoted by that time), which shows that the system thought it was a bit too short. :-) Dec 11, 2013 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.