Open matteyas opened 8 years ago
It is possible but then you have to write $cond in while once again.
macro WhileOtherwise(cond, body, otherwiseBody)
syntax ("while", "(", cond, ")", body, "otherwise", otherwiseBody)
{
<[
def firstHit = $cond;
while ($cond)
{
$body
}
when (!firstHit)
$otherwiseBody;
]>
}
Is that valid? The only changes is taking away firstHit = true;
inside the loop and setting firstHit to an immutable instead of a mutable.
Do you mean that using $cond twice is less efficient? That can't be the case; $cond will be evaluated on each loop anyway.
I am certainly open for other perspectives, but please explain. :smiley:
@matteyas $cond will be evaluated at least twice
macro without mutable might look like this:
macro WhileOtherwise(cond, body, otherwiseBody)
syntax ("while", "(", cond, ")", body, "otherwise", otherwiseBody)
{
<[
def loop(firstHit)
{
match ($cond, firstHit)
{
| false, true => $otherwiseBody;
| false, false => (); // end loop
| true, _ => $body; loop(false);
}
}
loop(true)
]>
}
@matteyas $cond
might have a mutating behavior, which would lead to very obscure bugs.
I noticed a very weird implementation in here: https://github.com/rsdn/nemerle/blob/master/macros/core.n
Look at the WhileOtherwise macro. First of all, it defines firstHit as a mutable. Secondly, it sets firstHit = true all the time (this will probably be optimized by the compiler, but still seems unnecessary).
Wouldn't it be possible to just use def firstHit = $cond instead? No need for a mutable variable, no need to set it in the loop. Maybe the language doesn't work that way?