💡 R and Perl are more alike than you think!Both use lexical scoping to create closures. The inner function "captures" the variable from the outer scope, creating a persistent environment.

#rstats
plus <- function(x) {
function(y) x + y
}
plus_one <- plus(1)
plus_one(10) #11

#perl
sub plus {
my ($x) = @_;
sub {
my ($y) = @_;
$x + $y
}
}
my $plus_one = plus(1);
$plus_one->(10); # 11
#FunctionalProgramming #CodingTips #ComputerScience

🔍 Spot the difference?

Both define an outer function (plus).

Both return an inner, anonymous function.

Both "close over" the variable in the parent scope.

R uses environments; Perl uses lexicals. Same logic, different syntax. 🤝

#FunctionalProgramming #CodingTips #ComputerScience #RStats #Perl

@ChristosArgyrop And the modern Perl syntax:
use v5.40;
sub plus ($x) {
sub ($y) {
$x + $y;
}
}