Eloquent way to iterate in Basic?

Blitz3D Forums/Blitz3D Programming/Eloquent way to iterate in Basic?

octothorpe(Posted 2005) [#1]
Let's say I want to implement a Prime Number Generator which returns a list of numbers, one at a time. I want to be able to run two or more generators simultaneously, so I can't use globals. I would imagine I'd need to implement three functions:

PNG_start.PNG(begin%, end%)
PNG_next(g.PNG)
PNG_get(g.PNG)

And use them like so:

g.PNG = PNG_start(1, 100)
While PNG_next(g)
	n = PNG_get(g)
	Print n
Wend


Three lines to start a loop seems excessive to me. Can anyone think of a more concise/eloquent way to write this? Or a better API?


Putting these statements on one line looks awful to me, mostly because the line doesn't start with a loop keyword so it's not immediately evident that a loop is beginning.

g.PNG = PNG_start(1, 100) : While PNG_next(g) : n = PNG_get(g)
	Print n
Wend


In C, you can use for(;;), which - although a little wordy - still looks good to me:

for( PNG g = PNG_start(1, 100); PNG_next(g); int n = PNG_get(g) ) {
	printf(n);
}



Any thoughts?


Tom(Posted 2005) [#2]
Basic is meant to be basic!

I think the first way is fine and much easier to read & understand. I find it takes me longer to read the second 2 ways.

Staggering curly braces in C/C++ is a pet hate of mine too :)


octothorpe(Posted 2005) [#3]
You'd probably hate my "cuddled" elses too ;)
} else {



octothorpe(Posted 2005) [#4]
I'm eager to cut down on the vertical space iteration requires because I find myself iterating a lot. Adding a psuedocode comment and separating the three lines from nearby code with blank lines seems to make me somewhat happy, but costs me even more vertical space!

something()

; for n = primes from 1 to 100
g.PNG = PNG_start(1, 100)
While PNG_next(g)
	n = PNG_get(g)

	something(n)
Wend

something()



big10p(Posted 2005) [#5]
[edit] forget it. I made a boo-boo. :)


BlackJumper(Posted 2005) [#6]
This suggestion may be scale-dependent... Have you considered a recursive definition of PNG_get() that takes care of the iterations ?

... depending on what you want to do with the numbers, you could 'process them' inside the recursive function and only return when you have cleared the stack. Possibly not much use if you need to get each one and work extensively with it before moving on to the next one. {As this will create non-abstract code that is bound to the specific implementation.}

... also (as mentioned) scale will be an issue if you have hundreds (thousands ?) of recursive calls on the stack before bottoming out.


octothorpe(Posted 2005) [#7]
As this will create non-abstract code that is bound to the specific implementation.


Precisely what I'm trying to avoid. ;)