nil*_*amo 19 php python lazy-evaluation
在Python(和其他)中,您可以通过在函数中使用'yield'运算符来递增地处理大量数据.在PHP中以类似的方式做什么?
例如,假设在Python中,如果我想读取一个可能非常大的文件,我可以一次一行地处理每一行(这个例子是设计的,因为它与'for file in file_obj基本相同) "):
def file_lines(fname):
f = open(fname)
for line in f:
yield line
f.close()
for line in file_lines('somefile'):
#process the line
Run Code Online (Sandbox Code Playgroud)
我现在正在做的(在PHP中)是我正在使用私有实例变量来跟踪状态,并且每次调用函数时都会相应地执行操作,但似乎必须有更好的方法.
Run*_*ard 18
在https://wiki.php.net/rfc/generators上有一个rfc 就是这样,它可能包含在PHP 5.5中.
与此同时,请查看在用户区实施的这种可怜的"发电机功能"的概念验证.
namespace Functional;
error_reporting(E_ALL|E_STRICT);
const BEFORE = 1;
const NEXT = 2;
const AFTER = 3;
const FORWARD = 4;
const YIELD = 5;
class Generator implements \Iterator {
private $funcs;
private $args;
private $key;
private $result;
public function __construct(array $funcs, array $args) {
$this->funcs = $funcs;
$this->args = $args;
}
public function rewind() {
$this->key = -1;
$this->result = call_user_func_array($this->funcs[BEFORE],
$this->args);
$this->next();
}
public function valid() {
return $this->result[YIELD] !== false;
}
public function current() {
return $this->result[YIELD];
}
public function key() {
return $this->key;
}
public function next() {
$this->result = call_user_func($this->funcs[NEXT],
$this->result[FORWARD]);
if ($this->result[YIELD] === false) {
call_user_func($this->funcs[AFTER], $this->result[FORWARD]);
}
++$this->key;
}
}
function generator($funcs, $args) {
return new Generator($funcs, $args);
}
/**
* A generator function that lazily yields each line in a file.
*/
function get_lines_from_file($file_name) {
$funcs = array(
BEFORE => function($file_name) { return array(FORWARD => fopen($file_name, 'r')); },
NEXT => function($fh) { return array(FORWARD => $fh, YIELD => fgets($fh)); },
AFTER => function($fh) { fclose($fh); },
);
return generator($funcs, array($file_name));
}
// Output content of this file with padded linenumbers.
foreach (get_lines_from_file(__FILE__) as $k => $v) {
echo str_pad($k, 8), $v;
}
echo "\n";
Run Code Online (Sandbox Code Playgroud)
Lui*_*mim 11
在用任何其他语言(包括PHP)实现之前,我用Python原型化所有内容.我最终使用回调来实现我的目标yield
.
function doSomething($callback)
{
foreach ($something as $someOtherThing) {
// do some computations that generates $data
call_user_func($callback, $data);
}
}
function myCallback($input)
{
// save $input to DB
// log
// send through a webservice
// etc.
var_dump($input);
}
doSomething('myCallback');
Run Code Online (Sandbox Code Playgroud)
这样每个$data
都传递给回调函数,你可以做你想要的.
归档时间: |
|
查看次数: |
8848 次 |
最近记录: |