Created
December 22, 2014 01:19
-
-
Save marcoonroad/96b69af02473a6496c6b to your computer and use it in GitHub Desktop.
Short arrow / lambda functions at Perl5...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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