문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top