Reputation: 3943
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
?
Upvotes: 3
Views: 130
Reputation: 206766
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 functions
?
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 }
.
Upvotes: 4
Reputation: 7415
For p
you can input any function with the signature => Boolean
, for s
you can input any function with the signature => Unit
.
So p
is the stop criterion for the while function. If your p
function evaluates to false
it breaks out of the while
loop, if it is true
, the body (the s
function) is called once and the while
function is called another time recursively with the same stop criterion (the p
function) and body.
Upvotes: 0