一段PHP版本的lambda实现
程序员文章站
2024-02-12 19:25:16
...
还有些缺陷,但能实现Church的自然数的lambda定义
class lambda{ private $f; private $args; private $count; public function __construct($f, $args = []) { if ($f instanceof lambda) { $this->f = $f->f; $this->count = $f->count; $this->args = array_merge($f->args, $args); } else { $this->f = $f; $this->count = count((new ReflectionFunction($f))->getParameters()); $this->args = $args; } } public function __invoke() { if (count($this->args) + func_num_args() count) { return new lambda($this, func_get_args()); } else { $args = array_merge($this->args, func_get_args()); $r = call_user_func_array($this->f, array_splice($args, 0, $this->count)); return is_callable($r) ? call_user_func(new lambda($r, $args)) : $r; } }}function lambda($f){ return new lambda($f);}$int1 = lambda(function($f, $x) { return $f($x);});$successor = lambda(function($p, $f, $x) { return $f($p($f, $x));});$add = lambda(function($p, $q, $f, $x) { return $p($f, $q($f, $x));});$mul = lambda(function($p, $q, $x) { return $p($q($x));});$exp = lambda(function($m, $n) { return $n($m);});$int2 = $successor($int1);$int3 = $add($int1, $int2);$int4 = $mul($int2, $int2);$int5 = $add($int2, $int3);$int6 = $mul($int3, $int2);$int7 = $add($int3, $int4);$int8 = $exp($int2, $int3);$int9 = $exp($int3, $int2);function p($num){ echo $num(function ($v){ return $v + 1; }, 0). "\n";}p($int1);p($int2);p($int3);p($int4);p($int5);p($int6);p($int7);p($int8);p($int9);