3 ms·
use bignum; use v5.10; =cut def Factorial(x): output = 1 for i in xrange(x): output *= (i + 1) return output =cut
by judofyr 14y ago
use bignum;
use v5.10;
=cut
def Factorial(x):
output = 1
for i in xrange(x):
output *= (i + 1)
return output
=cut
# Direct translation
sub factorial {
my $x = shift;
my $output = 1;
for my $i (1 .. $x) {
$output *= $i;
}
return $output;
}
say factorial(200);
=cut
def Factorial2(x):
return reduce(operator.mul, xrange(1, x + 1), 1)
=cut
use List::Util "reduce";
sub factorial2 {
my $x = shift;
reduce { $a * $b } (1 .. $x);
}
say factorial(200);
=cut
def Power(a, b):
if not b:
return 1
if b % 2:
return Power(a, b - 1) * a
x = Power(a, b/2)
return x * x
=cut
sub power {
my $a = shift;
my $b = shift // return 1;
if ($b % 2) {
return power($a, $b - 1) * $a
}
my $x = power($a, $b/2);
return $x * $x;
}
# lambda x: x + 7
my $plus7 = sub { $_[0] + 7 };
# Or:
my $plus7 = sub { my $x = shift; $x + 7 };
say $plus7->(14);
=cut
def TweakValue(x):
return x + 7
=cut
sub plus7 { $_[0] + 7 }
say plus7(14);
- colomon 14y agoJust in case anyone was wondering, in Perl 6: sub factorial($n) { my $output = 1; for 1..$n -> $i { $output *= $i; } $output; } or sub factorial2($n) { [*] 1..$n; } Pretty anonymous function to add a constant: -> $x { $x + 7 } Really short version: * + 7 Named: sub plus7($x) { $x + 7; }