码迷,mamicode.com
首页 > Web开发 > 详细

一段PHP版本的lambda实现

时间:2014-11-05 13:04:42      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:lambda   partial application   curry   

还有些缺陷,但能实现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);



一段PHP版本的lambda实现

标签:lambda   partial application   curry   

原文地址:http://blog.csdn.net/oyd/article/details/40820085

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!