File: 1482722504797.png (35.27 KB, 300x225, cartridge_handic_forth_c64_01.jpg)
File: 1482992105460.png (1.44 MB, 200x200, PRG76.pdf)
I've tried with begin..while..while..repeat but it's not legal, and I looked at words like exit and abort but those don't seem to work for what I need (exit breaks out of the function (word), next only works in a do..loop and abort signals an error).
( stuff )
( flag ) if ( I want out of the loop here ) then
( another flag ) if ( another exit here ) then
begin ( stuff ) ( flag ) if ( I want out of the loop here ) then ( another flag ) if ( another exit here ) then again
I simplified it to N and i though that was kind of dealt with some stack boilerplate which rendered the preparation and cleanup.
create #found 1 cells allot ( number of primes found so far )
create primelist 1000 cells allot
: prime? ( n -- flag )
( some preparation words )
N dup * i > if ( it's a prime, put 1 and leave ) then
N i mod 0= if ( not a prime put 0 and leave ) then
( next prime goes in i )
( cleanup ) ;
' (and failed miserably.
create primelist 100 cells allot ( space for 100 primes )
2 primelist ! ( our first prime yay! )
: prime? ( N -- )
primelist ( N addr )
over over @ ( N addr N i )
dup * < if 2drop -1 exit then \ it's prime!
over over @
mod 0= if 2drop 0 exit then \ it's composite
cell+ ( N addr+1 )
last case is because I'll be using another function to add the primes
3 prime . \ prints -1
4 prime . \ prints 0
5 prime . \ prints -1
15 prime . \ prints -1 whoopsie!
\ This goes at the top of the code
1 #found !
: addprime ( n -- )
primelist #found @ cells + !
1 #found +! ;
And that's my sieve.
: dummy ( n -- )
10 3 do
i prime? if i addprime then
\ primelist shoudl now hold 2 3 5 7
15 prime? . \ prints 0, yay!
total: 22 lines to get the 1000th prime.
dup prime? if dup addprime then
#found @ 1000 > until ;
primelist #found @ 1 - cells + @ . \ get the last prime
Only problem I have with forth in this respect is that you don't get to allocate things temporarily without making a mess, or so I've come to believe.
10 0 array \ this could allocate an array of 10 zeroes
dup 5 th 8 ! \ store an 8 at position 5
dup 3 th \ get the third element
dup .arr \ print the contents
\ and so on