Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain some scala code please - beginner

Tags:

scala

Reading http://www.scala-lang.org/docu/files/ScalaByExample.pdf

This piece of code :

def While (p: => Boolean) (s: => Unit) {
  if (p) { s ; While(p)(s) }
}

Is given this explanation :

The While function takes as first parameter a test function, which takes no parameters and yields a boolean value. As second parameter it takes a command function which also takes no parameters and yields a result of type Unit. While invokes the command function as long as the test function yields true.

Where is if (p) evaluated to true or false ?

Should the function s not be declared somewhere ? There is no code for function s ?

like image 868
user701254 Avatar asked May 21 '26 07:05

user701254


1 Answers

Where is if (p) evaluated to true or false ?

Exactly there, in that line.

p and s are call-by-name parameters, because of the => in front of them in the parameter lists of the method While. Every time their name is used in the body of While, they are evaluated.

Should the function s not be declared somewhere ? There is no code for function s ?

s is a parameter to the While method, just like p. (Why are you asking this question about s, but not about p?). Methods and functions in Scala can have multiple parameter lists. The While method has two parameter lists.

You call this While method by passing it something that evaluates to Boolean (the parameter p), and a block (the parameter s).

var i = 0
While (i < 5) {
  i = i + 1
  println(i)
}

In this example p is i < 5, a function that evaluates to a Boolean, and s is the block between the { and }.

like image 128
Jesper Avatar answered May 24 '26 05:05

Jesper