Just starting out? Need help? Post your questions and find answers here.
Joris
Addict
Posts: 885 Joined: Fri Oct 16, 2009 10:12 am
Location: BE
Post
by Joris » Wed Aug 19, 2020 2:04 pm
Hi,
The code below works fine, but I don't understand why it ends with the same string as the input.
Is that a normal thing with recursive, or how do I prevent that ?
Thanks.
Code: Select all
Procedure.s Analyse(txt.s)
Protected.i cnt, a
cnt=CountString(txt,":")
If cnt
For a=1 To cnt+1
Analyse(StringField(txt, a,":"))
Next
EndIf
Debug txt
EndProcedure
txt.s="testing 1 : testing 2 : testing 3"
Analyse(txt)
Yeah I know, but keep in mind ... Leonardo da Vinci was also an autodidact.
#NULL
Addict
Posts: 1440 Joined: Thu Aug 30, 2007 11:54 pm
Location: right here
Post
by #NULL » Wed Aug 19, 2020 2:18 pm
Because AFTER the recursion levels are unwound back to the first level, only then the first level will Debug its input string (from the first call)
Maybe this helps:
Code: Select all
Procedure.s Analyse(txt.s)
Protected.i cnt, a
Static level
level + 1
indent.s = Space(level*4)
Debug indent + "entering level " + level + ", input: " + txt
cnt=CountString(txt,":")
If cnt
For a=1 To cnt+1
Debug indent + "recurse.."
Analyse(StringField(txt, a,":"))
Next
EndIf
Debug indent + "exiting level " + level + ", input: " + txt
level - 1
EndProcedure
txt.s="testing 1 : testing 2 : testing 3"
Analyse(txt)
Joris
Addict
Posts: 885 Joined: Fri Oct 16, 2009 10:12 am
Location: BE
Post
by Joris » Wed Aug 19, 2020 3:23 pm
Ok.
So, it is a normal thing...
And I can prevent it with a ProcedureReturn.
I suppose that's a good sollution (it works, so...).
Thanks.
Code: Select all
Procedure.s Analyse(txt.s)
Protected.i cnt, a
cnt=CountString(txt,":")
If cnt
For a=1 To cnt+1
Analyse(StringField(txt, a,":"))
Next
ProcedureReturn ;<<<<<<<<<<<<<<<<
EndIf
Debug txt
EndProcedure
txt.s="testing 1 : testing 2 : testing 3"
Analyse(txt)
Yeah I know, but keep in mind ... Leonardo da Vinci was also an autodidact.
helpy
Enthusiast
Posts: 552 Joined: Sat Jun 28, 2003 12:01 am
Post
by helpy » Wed Aug 19, 2020 5:22 pm
For splitting up a string in to its fields you do not need recursive procedure.
The following code does the same
Code: Select all
Procedure.s Analyse(txt.s)
Protected.i cnt, a
Debug "----------------"
Debug "Analyse string: " + txt
cnt=CountString(txt,":")
If cnt
For a=1 To cnt+1
Debug StringField(txt, a,":")
Next
Else
Debug txt
EndIf
EndProcedure
txt.s="testing 1 : testing 2 : testing 3"
Analyse(txt)
txt.s="testing 1"
Analyse(txt)
Windows 10 / Windows 7
PB Last Final / Last Beta Testing