A PHP version of the lambda implementation ____php

Source: Internet
Author: User
Tags mul

There are some flaws, but the lambda definition of the natural number of church can be realized


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;
            The 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);}
$int 1 = 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);});
$int 2 = $successor ($int 1);
$int 3 = $add ($int 1, $int 2);
$int 4 = $mul ($int 2, $int 2);
$int 5 = $add ($int 2, $int 3);
$int 6 = $mul ($int 3, $int 2);
$int 7 = $add ($int 3, $int 4);
$int 8 = $exp ($int 2, $int 3);

$int 9 = $exp ($int 3, $int 2);
    function P ($num) {echo $num (function ($v) {return $v + 1; }, 0).
"\ n";
P ($int 1);
P ($int 2);
P ($int 3);
P ($int 4);
P ($int 5);
P ($int 6);
P ($int 7);
P ($int 8); P ($int 9);



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.