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

Identity Monad in Perl

#!/usr/bin/perl

sub wrap_value {
my $value=shift;
return sub {
return $value;
}
}

sub bind_func {
my ($value,$func)=@_;
return $func->($value);
}

sub lift_func {
my $func=shift;
return sub {
my $value=shift;
&bind_func($value,$func);
}
}

sub prefix {
my $value=shift;
return &wrap_value(“prefix ” . $value->());
}

sub suffix {
my $value=shift;
return &wrap_value($value->() . ” suffix”);
}

print &wrap_value(‘raja’)->(),”\n”;

print &bind_func(&wrap_value(‘raja’),\&prefix)->(),”\n”;

print &lift_func(\&prefix)->(&wrap_value(‘xyz’))->(),”\n”;

my $v=&wrap_value(‘123’);
my $p=&lift_func(\&suffix)->($v);
my $s=&lift_func(\&prefix)->($p);

print $s->(),”\n”;