6 Replies Latest reply on Nov 29, 2015 11:17 PM by user19752

# Recursive Calulation

I'm looking for a recursive calculation that would return 4-12-28-44-52 from a list that contains 4¶8¶16¶16¶8

• ###### 1. Re: Recursive Calulation

createString ( values ; runningTotal ) =

Let ( [

v = values

; s = GetAsNumber ( GetValue ( v ; 1 ) )

; r = RightValues ( v ; ValueCount ( v ) - 1 )

; runningTotal = runningTotal+ s

] ;

runningTotal

& Case (

not IsEmpty ( r )

; "-"

& createString ( r ; runningTotal)

)

)

Chris Cain

Extensitech

• ###### 2. Re: Recursive Calulation

Thanks for the help

• ###### 3. Re: Recursive Calulation

Chris is right on top of things and that recursive calc works great for a Custom Function.  I'm not sure why, but I tend to only use Custom Functions for a few specific needs like json/xml manipulation and probably would not have for a case like this. Just a personal preference.  So if it were me, I would just write it into the script or make it subscript of something like this:

Set Variable [ \$Input ; Value: "4¶8¶16¶16¶8" ]

Set Variable [ \$n ; Value: ValueCount ( \$Input ) ]

Loop

Set Variable [ \$i ; Value: \$i + 1 ]

Exit Loop If [ \$i > \$n ]

Set Variable [ \$Value ; Value: GetValue ( \$Input ; \$i ) ]

Set Variable [ \$S ; Value: \$S + \$Value ]

Set Variable [ \$Result ; Value: \$Result & "-" & \$S ]

End Loop

Set Variable [ \$Result ; Value: Middle ( \$Result ; 2 ; Length ( \$Result ) ) ]

Exit Script [ Result: \$Result ]

• ###### 4. Re: Recursive Calulation

Thanks for your input. I had no problem coming up with a script that did the job. I knew it also could be done with a recursive calulation but couldn't wrap my head it and it was driving me bonkers.

• ###### 5. Re: Recursive Calulation

I know how that is, madkins.  Which is probably because I don't do many recursive Custom Functions.  I always find myself having to brush up on it just before the FM certification each time <grin>

• ###### 6. Re: Recursive Calulation

I made "tail recursion" version for fun.

runningTotal ( values; one )

//should be called one as 1

Let ( [

n = ValueCount ( values ) ;

t = GetValue ( values ; one - 1 ) + GetValue ( values ; one )

] ;

Case (

one > n ; "?" ;

one = n ; Substitute ( LeftValues ( values ; n - 1 ) ; ¶ ; "-" ) & t ;

runningTotal ( LeftValues ( values ; one - 1 ) & t & ¶ & RightValues ( values ; n - one ) ; one + 1 )

)

)