Swaroop Sridhar wrote:
> I think we can have a construct similar to the standard for loop:
> initialie ; condition ; step ; return
> for(i=<init1>, j=<init2>, ... ; <cond> ; i = <step1>, ...; <ret-value>){
>
> }
>
The C-for loop is one construct that I think BitC could do without. I've
encountered and fixed numerous bugs throughout my career stemming from
things like:
for (int i = 0; i < n; j++)
do_something(i);
Do you spot the error? How quickly do you spot it?
The Pascal/Fortran/OCaml approach is to make sure you reference the loop
variable only once (except in the loop body), and this means less errors
of the above sort:
for i = 0 to n - 1 do ...
done
Now, this is good and all for imperative sequential code, but I now much
prefer F#'s "pipe" idioms (composition of functions done the natural
way), SML's usage of higher-order functions such "map", "fold", "iter"
and "concat". The reason that it turns out more readable is that the
words indicate the purpose of the loop, whereas for-loops have to be
mentally parsed for the meaning.
As an example, if the language had the concept of "generators" (a-la
Python's yield), then something like this is quite readable:
{0 .. n-1} |> iter (fun i -> printf "%d\n" i) // Generate integers
from 0 to n - 1, and iterate the print function for each element.
{1 .. n} |> fold (fun acc i -> acc * i) 1 // Generate integers
from 1 to n, accumulating the product (i.e. 1*2*...*n).
Another interesting idea is to make a distinction between "let rec"
constructs (that may not be tail-recursive) and loops. For instance, by
inventing "let loop <label>(<loop-variables>) = ... in":
let fun power(x: float, n: int32): float =
let loop pow_loop(x:float, n:uint32): float =
if n = 1 then x
else if n &&& 1 = 0 then pow_loop(x*x, n/2)
else x * pow_loop(x*x, n/2)
in
if n < 0 then 1.0 / pow_loop(x, -n)
else if n = 0 then if x != 0.0 then 1.0 else NaN
else pow_loop(x, n)
[By the way - yes, I know the above code has a bug in it. Hint: There
are two (signed) integers with the property -n = n.]
Thanks,
PKE.
--
Pål-Kristian Engstad ([email protected]),
Lead Graphics & Engine Programmer,
Naughty Dog, Inc., 1601 Cloverfield Blvd, 6000 North,
Santa Monica, CA 90404, USA. Ph.: (310) 633-9112.
"Emacs would be a far better OS if it was shipped with
a halfway-decent text editor." -- Slashdot, Dec 13. 2005.
_______________________________________________
bitc-dev mailing list
[email protected]
http://www.coyotos.org/mailman/listinfo/bitc-dev