當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


PHP Ds Deque reduce()用法及代碼示例



Ds\Deque::reduce() 函數可以使用回調函數將雙端隊列減少到單個值。

用法

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

Ds\Deque::reduce() 函數可以返回最終回調的值。

例子1

<?php 
   $deque = new \Ds\Deque([10, 20, 30, 40, 50]); 
   echo("The elements in deque:\n"); 
   print_r($deque); 
   
   $func = function($carry, $element) { 
      return $carry + $element; 
   }; 
   echo("\n The deque after reduced into single element:");   
   var_dump($deque->reduce($func, 3)); 
?>

例子2

<?php 
   $deque = new \Ds\Deque([10, 20, 30, 40, 50]); 
   echo("The elements in deque:\n"); 
   print_r($deque); 
   
   $func = function($carry, $element) { 
      return $carry * $element + 30; 
   }; 
   echo("\n The deque after reduced into single element:"); 
   var_dump($deque->reduce($func, 10)); 
?>

相關用法


注:本文由純淨天空篩選整理自 PHP - Ds Deque reduce() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。