Recursive problem ...

Just starting out? Need help? Post your questions and find answers here.
Joris
Addict
Addict
Posts: 885
Joined: Fri Oct 16, 2009 10:12 am
Location: BE

Recursive problem ...

Post by Joris »

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
Addict
Posts: 1440
Joined: Thu Aug 30, 2007 11:54 pm
Location: right here

Re: Recursive problem ...

Post by #NULL »

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
Addict
Posts: 885
Joined: Fri Oct 16, 2009 10:12 am
Location: BE

Re: Recursive problem ...

Post by Joris »

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.
User avatar
helpy
Enthusiast
Enthusiast
Posts: 552
Joined: Sat Jun 28, 2003 12:01 am

Re: Recursive problem ...

Post by helpy »

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
Post Reply