Generating Church Numbers with Perl

At the moment I am concentrating on other projects so I dont have that much additional code, but at least I will give a version in Perl now. I am working on a PHP-Version (for Versions below 5.3, above 5.3 it should be easy), a Version in MS Quick Basic (dont know if this will work, at least it needs a bit hacking), and on a Version in Prolog. If you happen to have own code for this, please let me know.

I looked up some methods of creating functions from this site. Anyway, my code may be similar, but I wrote it myself.

$churchZero = sub {
    my $f = shift;
    return sub {my $x = shift; return $x;};
};

$churchSucc = sub {
    my $n = shift;
    return sub {
        my $f = shift;
        return sub {
            my $x = shift;
            return $f->($n->($f)->($x));
        };
    };
};

$incf = sub {
    my $x = shift;
    return $x+1;
};

sub toChurch {
    my $n = shift;
    $ret=$churchZero;
    for ($i=0; $i<$n; $i++) {
        $ret=$churchSucc->($ret);
    };
    return $ret;
};

printf "%dn", toChurch(10)->($incf)->(0);

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s

%d Bloggern gefällt das: