我正在尝试在hack中实现下划线的reduce功能。在下划线中,reduce 函数具有以下行为:
如果没有 memo 传递给 reduce 的初始调用,则不会在列表的第一个元素上调用 iteratee。相反,第一个元素在列表中的下一个元素上的 iteratee 调用中作为备忘录传递。
我尝试实现该功能:
function reduce<T, Tresult>(
Iterable<T> $iterable,
(function(?Tresult, T):Tresult) $fn,
?Tresult $memo=null):?Tresult {
if (is_null($memo)) {
$memo = $iterable->firstValue();
$iterable = $iterable->skip(1);
}
foreach ($iterable as $value) {
$memo = $fn($memo, $value);
}
return $memo;
}
这会导致错误:
Invalid return type (Typing[4110])
This is a value of generic type Tresult
It is incompatible with a value of generic type T
via this generic Tv
我如何告诉类型检查器T == Tresult
何时is_null($memo)