test.php
<?php
    function reverseStr($word,$reword){
        if(strlen($word)<1){
            return $reword;
        }
        return reverseStr(substr($word,0,-1), $reword.$word[-1]);
    }
    $word = "abcdefgh";
    echo reverseStr($word, null);
    //hgfedcba
    echo strlen("");
    //0
?>
There are various types of recursive functions, but they are created with tail recursion in mind. This will be explained while comparing the differences with ordinary recursive functions.
__ Prerequisite: Input value is abcd __
test.php
<?php
    function a($word,$reword){
        if(strlen($word)<1){
            return $reword;
        }
        return a(substr($word,0,-1), $reword.$word[-1]);
    }
?>
The transition of the function assumed when the initial input value is (abcd, "") is as follows. a(abcd,"") => a(abc,d) => a(ab,dc) => a(a,dcb) => a("",dcba) => dcba It can be said that the load on the memory is small because the values are returned one by one and the processing is executed.
__ Prerequisite: Input value is abcd __
test.php
<?php
   function a($word){
        if(strlen($word)<1){
            return $word;
        }
        return $word[-1] + a(substr($word,0,-1));
    }
?>
The transition of the function assumed when the initial input value is (abcd, "") is as follows. a(abcd) => a(abcd){ d + a(abc) } => a(abcd){ d + a(abc) { c + a(ab) } } => a(abcd){ d + a(abc) { c + a(ab) { b + a(a) } } } => a(abcd){ d + a(abc) { c + a(ab) { b + a } } } => a(abcd){ d + a(abc) { c + ba } } => a(abcd){ d + cba } =>dcba
test.js
  function reverseStr(word, reword){
      if(word.length < 1){
          return reword;
      }
      return reverseStr(word.slice(0,-1), reword + word.slice(-1));
  }
  var word = "abcdefgh";
  console.log(reverseStr(word, ""));
test.rb
def reverseStr(word, reword)
   if(word.length < 1)
       return reword
   end
   return reverseStr(word[0..-2],reword+word[-1])
end
word = "abcdefgh"
puts reverseStr(word, "")
test.py
def reveseStr(word, reword):
    if len(word) < 1:
        return reword
    return reveseStr(word[0:-1], reword + word[-1])
    
word = "abcdefgh"
print(reveseStr(word, ""))
        Recommended Posts