coding is fine,but i did not understood how it works

shireeshn

Member
reversing of string, output is comming correct.

FUNCTION rev RETURNS CHAR(INPUT ll AS CHAR).
IF LENGTH(ll) = 1 THEN
RETURN ll.
ELSE
DO:

RETURN rev(SUBSTRING(ll,2)) + SUBSTRING(ll,1,1).
END.
END.
DISP rev("shireesh").


can any one explain me how it works.
 
ah good old recursive function :-)

Maybe you understand it better if you run this. You get a message at each stage the return value is formed.

Code:
DEFINE VARIABLE cTmp AS CHARACTER   NO-UNDO.
FUNCTION rev RETURNS CHAR(INPUT ll AS CHAR).
    MESSAGE cTmp
        VIEW-AS ALERT-BOX INFO BUTTONS OK.
    IF LENGTH(ll) = 1
    THEN DO:
        ASSIGN cTmp  = ll + cTmp.
        MESSAGE 'finally: ' + cTmp
            VIEW-AS ALERT-BOX INFO BUTTONS OK.
        RETURN ll.
    END.
    ELSE do:
        ASSIGN cTmp = SUBSTRING(ll,1,1) + cTmp.
        RETURN rev(SUBSTRING(ll,2)) + SUBSTRING(ll,1,1).
    END.
END.
DISP rev("shireesh") cTmp.
In essence the function is called until the length of the input value is 1.
To show that, I introduced a variable cTmp which shows how the final return value is formed.
As you can see the function calls itself until the length of the input value is 1 and then it returns to the caller.

I hope this clarifies the function a bit more.

Casper.
 
It is using a recursive method to concatenate the string
The function is calling itself repeatedly until it is finished.

There are two cases: It has finished (the return ll) or it is not finished.

In the case it is not yet finished doing the job, it is calling itself each time with one less beginning character (the rev(SUBSTRING(ll,2)) part) and returning this to itself plus the current first character. (the SUBSTRING(ll,1,1) part). The parenthesis placement are important since we only want to pass the remaining portion of the string back to itself until it is finished.

Do notice that substring is called two different ways, once to get exactly one character. (the current first character) and the second way with only one numeric argument to get the string from position two and on (substring( ll,2))

Better explanation of recursion:
http://en.wikipedia.org/wiki/Recursion#Recursion_in_computer_science
 
casper it not clear fully, ur program is clear but in this statment

RETURN rev(SUBSTRING(ll,2)) + SUBSTRING(ll,1,1).

1) in every statment is it returns some value or calling function again or both ?

2) where does this string get added ?
 
Back
Top