[REBOL] while statement problem Re:(3)
From: joel:neely:fedex at: 3-Oct-2000 11:06
Hello, Joe!
[capolunghi--att--com] wrote:
> Petr:
>
> Thanks. Your solution led me to conclude that you can't do this:
>
> prime : true
> while [ prime and ... ] [ .. ]
>
> Seems rebol does not interpret 'prime as true in this case. The workaround
> is to state:
> while [ (prime = true) and (...) ] [ .. ]
>
> You have to explicitly state the conditions in the while clause. Strange ..
>
Not at all! (Pardon the pun! ;-)
All of these work:
>> use [nonseven counter total] [
[ nonseven: 7 <> counter: total: 0
[ while [all [nonseven total < 50]] [
[ total: total + counter
[ nonseven: 7 <> counter: counter + 1
[ ]
[ print [nonseven counter total]
[ ]
false 7 21
(bailing out when nonseven becomes false)
>> use [nonseven counter total] [
[ nonseven: 7 <> counter: total: 0
[ while [all [nonseven total < 10]] [
[ total: total + counter
[ nonseven: 7 <> counter: counter + 1
[ ]
[ print [nonseven counter total]
[ ]
true 5 10
(or bailing out when total hits the stated limit)
>> use [nonseven counter total] [
[ nonseven: 7 <> counter: total: 0
[ while [nonseven and (total < 10)] [
[ total: total + counter
[ nonseven: 7 <> counter: counter + 1
[ ]
[ print [nonseven counter total]
[ ]
true 5 10
(or doing this with and instead of all in the control expression)
I think Petr read your code:
> >
> > while [ prime and test <= square-root number ] [..]
> >
as intending to control on "while prime and test are both at most
square-root of number" which is what his reply actually does:
> while [ all [(prime <= square-root number) (test <= square-root number)]
> ....
> parens () nod needed ...
>
> not sure if it's what you wanted to achieve ...
>
> btw: and should work imho too, just use parens ...
>
> while [(prime <= square-root number) and (test <= square-root number)] ....
>
The REAL root cause of your error message is that REBOL doesn't use
operator precendence (as other programming languages do). Consecutive
operators are evaluated left-to-right, meaning that your original:
prime and test <= square-root number
is evaluated with the same meaning as
(prime and test) <= square-root number
which would try to apply and to a boolean and a number (and then would
try to apply <= between a boolean and a number, but we don't get that far).
The first of these generates the show-stopping error, as in:
>> use [nonseven counter total] [
[ nonseven: 7 <> counter: total: 0
[ while [nonseven and total < 10] [
[ total: total + counter
[ nonseven: 7 <> counter: counter + 1
[ ]
[ print [nonseven counter total]
[ ]
** Script Error: Expected one of: logic! - not: integer!.
** Where: nonseven and total < 10
Hope this helps!
-jn-
--
; Joel Neely [joel--neely--fedex--com] 901-263-4460 38017/HKA/9677
REBOL [] print to-string debase decompress #{
789C0BCE0BAB4A7176CA48CAB53448740FABF474F3720BCC
B6F4F574CFC888342AC949CE74B50500E1710C0C24000000}