github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/execution/testdata-shanghai/tail-recursion.sol (about)

     1  // SPDX-License-Identifier: GPL-3.0
     2  
     3  pragma solidity ^0.8.14;
     4  
     5  contract MyContract {
     6      // naive recursion
     7      function sum(uint256 n) public returns (uint256) {
     8          return n == 0 ? 0 : n + sum(n - 1);
     9      }
    10  
    11      // loop
    12      function sumloop(uint256 n) public pure returns (uint256) {
    13          uint256 total = 0;
    14          for (uint256 i = 1; i <= n; i++) {
    15              total += i;
    16          }
    17          return total;
    18      }
    19  
    20      // tail-recursion
    21      function sumtailHelper(uint256 n, uint256 acc) private returns (uint256) {
    22          return n == 0 ? acc : sumtailHelper(n - 1, acc + n);
    23      }
    24  
    25      function sumtail(uint256 n) public returns (uint256) {
    26          return sumtailHelper(n, 0);
    27      }
    28  }