Skip to content

Instantly share code, notes, and snippets.

@marcoonroad
Created December 22, 2014 01:19
Show Gist options
  • Save marcoonroad/96b69af02473a6496c6b to your computer and use it in GitHub Desktop.
Save marcoonroad/96b69af02473a6496c6b to your computer and use it in GitHub Desktop.
Short arrow / lambda functions at Perl5...
use v5.12;
use utf8;
use strict;
use warnings;
# to declare short arrow functions
sub Ω {
my $in = shift;
return sub {
my $out = shift;
my $old = $@;
$@ = "";
my $sub = eval "sub {
my ($in) = \@_;
return $out;
}";
if ($@) {
my $err = $@;
$@ = $old;
return die $err;
}
else {
$@ = $old;
return $sub;
}
}
}
# to declare short lambdas
sub λ {
my $str = shift;
if ($str =~ /(.*):(.*)/) {
my ($in, $out) = ($1, $2);
my $old = $@;
$@ = "";
my $sub = eval "sub {
my ($in) = \@_;
return $out;
}";
if ($@) {
my $err = $@;
$@ = $old;
return die $err;
}
else {
$@ = $old;
return $sub;
}
}
return die "Bad signature!";
}
my $incr = Ω ('$x') -> ('$x + 1');
say &$incr (4); # ---> 5
say &{ λ q| $x, $y: $x + $y | } (5, 10); # ---> 15
# end of script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment