Skip to content

Recursion

Tim Hardcastle edited this page Feb 29, 2024 · 5 revisions

The iterators in Charm should keep you from having to use recursion unless it is really necessary.

But when you do want to, you can. The file examples/recursion.ch contains a recursive factorial function and a recursive Fibonacci function:

def

factorial (n int) : 
    n == 0 : 
        1
    else n * factorial n - 1 

fib(n) : 
    n in {0, 1} : 
        1
    else : 
        fib(n - 1) + fib(n - 2)

In anonymous functions, you can use the word this to refer to the function you're in, allowing it to call itself.

FACTORIAL = func(n int) :
    n == 0 : 
        1
    else :
        n * this n - 1 
Clone this wiki locally