简体   繁体   中英

How can I make this function tail recursive?

I'm wondering if my algorithm is tail recursive; I've just made this function to pretty print an array in PHP:

function get_pretty_output($value, $first=true, $indent = ''){
    if (!is_array($value)) { return $value.PHP_EOL; }
    if (empty($value)) { if ($first) { return 'Array()'.PHP_EOL; } else { return preg_replace('/    /', '', $indent, 1).')'.PHP_EOL; }}
    if ($first) {
            $output = 'Array'.PHP_EOL.$indent.'('.PHP_EOL;
            $indent .='    ';
            $first = false;
    } else {
        $output = '';
    }
    reset($value);
    $key = key($value);
    return $output .= $indent . 
        '[' . 
        $key . 
        '] => ' . 
        get_pretty_output(array_shift($value), true, $indent) . 
        get_pretty_output($value, $first, $indent);
}

because neither

$pretty_string = print_r($array, true);

nor

ob_start(); 
var_dump($array); 
$pretty_string = ob_get_contents(); 
ob_end_clean();

seem to work when the client disconnects even with ignore_user_abort(true) (PHP 5.6).

I don't even know if PHP benefits from tail recursion (I was told it doesn't), but anyway I would like to know if this would be a valid example. I don't think so (it needs to save the function context to use on the second call), but I don't seem to be able to find an equivalent tail recursive algorithm. Is there a method I can follow?

This would not be an example of tail recursion because computation is still being done in the earlier recursive calls AFTER the value is return. Consider the example provided in a previous StackOverflow post ( What is tail recursion? ). In this case, the ".=" operator would complete a concatenation and THEN return the result in the function.

To make this tail recursive you would want to modify your code print the 'output' variable prior to making the recursive call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM