遞迴 - 看遞迴

遞迴很容易 - 從程式內部來看程式本身。但是如果你遞得太多,那麼堆疊將會耗盡空間。

一個程式計算階乘。

PROCEDURE factorial:
    DEFINE INPUT  PARAMETER piNum AS INTEGER     NO-UNDO.
    DEFINE OUTPUT PARAMETER piFac AS INTEGER     NO-UNDO.

    DEFINE VARIABLE iFac AS INTEGER     NO-UNDO.

    IF piNum = 1 THEN DO:
        pifac = 1.
    END.
    ELSE DO:
        RUN factorial(piNum - 1, OUTPUT iFac).
        piFac = piNum * iFac.
    END.

END PROCEDURE.

DEFINE VARIABLE f AS INTEGER     NO-UNDO.

RUN factorial(7, OUTPUT f).

DISPLAY f.