← Back to lessons

22 Recursion

Intermediate

Cangjie supports recursive functions.

Simple function calculating factorial of a number.

We can declare function inside functions, and they can also be recursive. This function calculates fibonacci numbers.

We can assign a function to a variable, and use it as an alias for that function.

Lambda functions have no way of calling themselves, because they have no name. Variables that would store them are initialized after the definition is analyzed by the compiler. So compiler reports undeclared identifier power_of_2.

recursion.cj
func fact(n: Int64): Int64 {
    if (n == 0) {
        return 1
    }
    return n * fact(n - 1)
}

main() {
    println(fact(7))

    func fibonacci(n: Int64): Int64 {
        if (n < 2) {
            return n
        }
        return fibonacci(n - 1) + fibonacci(n - 2)
    }
    let fib: (n: Int64) -> Int64 = fibonacci
    println(fib(7))
}

// Output:
// let power_of_2: (Int64)->Int64 = {exp:Int64 =>
//     if(exp == 0)
//     {
//         return 1
//     }
//     return 2*power_of_2(exp-1)
// }