Ds \ Deque::reduce()函數是PHP中的一個內置函數,用於使用回調函數將Deque減少為單個元素。
用法:
public Ds\Deque::reduce( $callback, $initial ):mixed
參數:該函數接受上述和以下所述的兩個參數:
- callable:它包含對Deque元素要執行的操作,從而生成一個元素。
- value:它保留進位的初始值,該值將是對所有元素執行運算後的結果。
返回值:該函數返回回調函數返回的最終值。
以下示例程序旨在說明PHP中的Ds \ Deque::reduce()函數:
程序1:
<?php
// Declare a deque
$deck = new \Ds\Deque([10, 20, 30, 40, 50, 60]);
echo("Elements of Deque\n");
// Display the Deque elements
print_r($deck);
// Function to perform operation on deque
$func = function($carry, $element) {
return $carry + $element;
};
echo("\nDeque after reduced into single element:");
// use reduce() function
var_dump($deck->reduce($func, 5));
?>
輸出:
Elements of Deque Ds\Deque Object ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [5] => 60 ) Deque after reduced into single element:int(215)
程序2:
<?php
// Declare a deque
$deck = new \Ds\Deque([10, 20, 30, 40, 50, 60]);
echo("Elements of Deque\n");
// Display the Deque elements
print_r($deck);
// Function to perform operation on deque
$func = function($carry, $element) {
return $carry * $element + 20;
};
echo("\nDeque after reduced into single element:");
// use reduce() function
var_dump($deck->reduce($func, 10));
?>
輸出:
Elements of Deque Ds\Deque Object ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [5] => 60 ) Deque after reduced into single element:int(8714461220)
參考: http://php.net/manual/en/ds-deque.reduce.php
相關用法
- PHP Ds\Map reduce()用法及代碼示例
- PHP Ds\Set reduce()用法及代碼示例
- PHP Ds\Vector reduce()用法及代碼示例
- PHP Ds\Sequence reduce()用法及代碼示例
- Javascript Array reduce()用法及代碼示例
- PHP tan( )用法及代碼示例
- d3.js d3.sum()用法及代碼示例
- d3.js d3.mean()用法及代碼示例
- PHP exp()用法及代碼示例
注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 PHP | Ds\Deque reduce() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。