skx / gobasic

A BASIC interpreter written in golang.
https://blog.steve.fi/tags/basic/
GNU General Public License v2.0
328 stars 27 forks source link

Troubleshoot recursive GOSUB program #85

Closed udhos closed 5 years ago

udhos commented 5 years ago

For some reason, gobasic can't properly execute this recursive factorial program. It doesn't ever end. Why?

$ gobasic fact.bas 
This program calculates factorial recursively using GOSUB
Enter number: 7
Calculating factorial for  7 !
^C
$ more fact.bas 
10 print "This program calculates factorial recursively using GOSUB\n"
20 input "Enter number: ", x
30 print "Calculating factorial for ", x, "!\n"
40 gosub 100
50 print "Done: ", x, "! = ", y, "\n"
60 end
100 rem Factorial for x is returned in y
110 rem Input: x
120 rem Output: y
130 if x < 2 then y = 1
135 if x < 2 then return
140 x = x - 1
150 gosub 100
160 x = x + 1
170 y = y * x 
180 return
skx commented 5 years ago

If you update the program to add LET it will work:

Lines 130, 160 & 170:

  10 print "This program calculates factorial recursively using GOSUB\n"
  20 input "Enter number: ", x
  30 print "Calculating factorial for ", x, "!\n"
  40 gosub 100
  50 print "Done: ", x, "! = ", y, "\n"
  60 end
  100 rem Factorial for x is returned in y
  110 rem Input: x
  120 rem Output: y
  130 if x < 2 then LET y = 1
  135 if x < 2 then return
  140 let x = x - 1
  150 gosub 100
  160 let x = x + 1
  170 let y = y * x
  180 return

For me it seems better that way:

  frodo ~ $ gobasic fact.bas
  This program calculates factorial recursively using GOSUB
  Enter number: 6
  Calculating factorial for  6 !
  Done:  6 ! =  720 

  frodo ~ $ gobasic fact.bas
  This program calculates factorial recursively using GOSUB
  Enter number: 150
  Calculating factorial for  150 !
  Done:  150 ! =  57133839564458504888431685060296571931908532210186455865803960270646722738367142315408067529343188252533443527449112321315901238165762616382826568957034327205350825860530274233419660272647262828623211661421621408605336881542803886698113566366770204591606248505344.000000 

Of course it should report an error about the other bits being unknown/bogus (compare #80 ).

udhos commented 5 years ago

Great, I managed to forgot that LET is required. Thanks!

skx commented 5 years ago

And I didn't notice you were the same person who reported the issue about making LET optional!

Maybe this is enough to make me reconsider..