PHP - Ds Vector::reduce() 函式



PHP 的 Ds\Vector::reduce() 函式透過對每個向量元素應用回撥函式來將向量簡化為單個值。回撥函式是一個對每個向量元素進行操作並返回結果的函式。

如果指定了初始引數值,則回撥函式將從此初始值開始,並繼續處理每個向量元素,將它們組合起來生成最終結果,最終簡化為單個值。

語法

以下是 PHP Ds\Vector::reduce() 函式的語法:

public mixed Ds\Vector::reduce( callable $callback [, mixed $initial ] )

引數

以下是此函式的引數:

  • callback - 回撥函式對每個向量元素進行操作。
  • initial - 傳遞值的初始值,可以為 null。

以下是callback函式的語法:

callback(mixed $carry, mixed $value): mixed

返回值

此函式返回最終回撥函式的值。

示例 1

以下是 PHP Ds\Vector::reduce() 函式的基本示例:

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo("The original vector elements: \n"); 
   print_r($vector);
   echo("The vector reduce to single value is: "); 
   print_r($vector->reduce(function($carry, $element) { 
      #adding
      return $carry + $element;
   }));
?>

輸出

以上程式產生以下輸出:

The original vector elements:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The vector reduce to single value is: 15

示例 2

如果我們提供初始值,則回撥函式將從此值開始,然後繼續處理向量元素。

以下是 PHP Ds\Vector::reduce() 函式的另一個示例。我們使用此函式將此向量 ([1, 2, 3, 4, 5]) 簡化為單個值:

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);  
   echo("The original vector elements: \n"); 
   print_r($vector); 
   $func = function($carry, $element) { 
      return $carry  * $element; 
   }; 
   echo("The vector after reducing to single element: "); 
   print_r($vector->reduce($func, 10));
?>

輸出

執行以上程式後,將顯示以下輸出:

The original vector elements:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The vector after reducing to single element: 1200
php_function_reference.htm
廣告