Lambda Calculus in Perl

#!/usr/bin/perl
# lambda expression = anonymous subroutine
# all subroutines defined in this file are anonymous
my $apply = sub { # lift
  my ($func,@args)=@_;
  sub {$func->(@args,@_)} # bind
};
my $identity = sub { # wrap
  my $value=shift;
  sub {$value}
};
my $self_apply = sub {
  my $func=shift;
  $apply->($func,$func);
};
my $do_pipe = sub {
  my $out=shift;
  for(@_){$out=$_->($out);}
  $out
};
my $say    = sub {print shift->(),”\n”};
my $prefix = sub {$identity->(“prefix ” . shift->())};
my $suffix = sub {$identity->(shift->() . ” suffix”)};
print $identity->(‘raja’)->(),”\n”;
print $apply->($prefix)->($identity->(‘xyz’))->(),”\n”;
my $v=$identity->(‘123’);
my $p=$apply->($suffix)->($v);
my $s=$apply->($prefix)->($p);
$say->($s);
$do_pipe->(
  ‘456’,
  $identity,
  $suffix,
  $prefix,
  $say
);
$self_apply->(
  sub {
    my ($decr,$in)=@_;
    if(!$in){return;}
    print “$in\n”;
    $decr->($decr,$in-1);
  }
)->(7);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s