2

I need to call a recursive function with if statements. Is this possible in Solidity? Please provide an example.

5

It is possible to use recursive functions in Solidity. The following is a simple recursive function in solidity

pragma solidity ^0.5.12;

contract Test {
    uint x;
    function set(uint y) public {
        x = y;
    }

    function factorial(uint y) internal pure returns(uint){
        if (y == 1){
            return y;
        } else {
            return y * factorial(y-1);
        }
    }

    function get() public view returns(uint){
        return factorial(x);
    }
}

But please be aware that you should know what you are doing since recursive functions can end up costing huge gas and cause the transaction to revert atomically.

3
  • One thing worth to note is : Gas requirement of function Test.get() high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage) – Vishwa Ratna Oct 11 '19 at 13:19
  • I have mentioned the word of caution in my answer. – Sanjay S B Oct 11 '19 at 13:22
  • Worth noting that if you want this to work externally as well, you need to switch the function to "public". – logankilpatrick Mar 11 at 16:30
2

Fibonacci is perfect example to illustrate the recursion(tail):

Mathematically, the Fibonacci sequence is a recursive function that adds the previous elements to obtain the next element, Like below:

Fn = Fn-1 + Fn-2

function fib(uint n) public view returns(uint) { 
    if (n <= 1) {
       return n;
    } else {
       return this.fib(n - 1) + this.fib(n - 2);
    }
}

Note: Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.