• 技术文章 >后端开发 >php教程

    一段PHP版本的lambda实现

    2016-06-23 13:46:16原创461
    还有些缺陷,但能实现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() < $this->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);
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:二维码解析后文字乱码 下一篇:求php校园二手交易网源码,求完整可用,,万分感谢
    20期PHP线上班

    相关文章推荐

    精选22门好课,价值3725元,开通VIP免费学习!• 细思极恐?关于in_array的第3个参数• 关于HTML登陆界面的有关问题。• 今天又犯2了-小弟我不是在犯2,就是在犯2的路下• 关于PHP传值与传引用的奇怪有关问题• 建站之三:PHP网页兑现
    1/1

    PHP中文网