Skip to content

Commit

Permalink
implementing the suggestion for 0! given in #581
Browse files Browse the repository at this point in the history
  • Loading branch information
szabgab committed Sep 13, 2023
1 parent 5d33ba8 commit f06aa98
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 17 deletions.
11 changes: 11 additions & 0 deletions examples/factorial.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use strict;
use warnings;
use 5.010;

my $n = shift // die "Usage: $0 N\n";

my $f = 1;
my $i = 1;
$f *= ++$i while $i < $n;
say $f;

18 changes: 18 additions & 0 deletions examples/factorial_with_reduce.pl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use strict;
use warnings;
use 5.010;

use List::Util qw(reduce);

my $n = shift // die "Usage: $0 N\n";

{
my $fact = reduce { $a * $b } 1 .. $n;
say $fact;
}

{
# handles 0! = 1 as well
my $fact = $n == 0 ? 1 : reduce { $a * $b } 1 .. $n;
say $fact;
}
21 changes: 4 additions & 17 deletions sites/en/pages/factorial-in-perl.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,19 @@ I was working on some examples when I had to calculate <hl>factorial</hl>. (<hl

The solution without any modules:

<code lang="perl">
use strict;
use warnings;
use 5.010;

my $f = 1;
my $i = 1;
my $n = 4;
$f *= ++$i while $i < $n;
say $f;
</code>

<include file="examples/factorial.pl">

The solution when using the <hl>reduce</hl> function of the
standard <a href="https://metacpan.org/pod/List::Util">List::Util</a> module:

<code lang="perl">
use List::Util qw(reduce);
my $fact = reduce { $a * $b } 1 .. $n;
say $fact;
</code>
<include file="examples/factorial_with_reduce.pl">

<hl>reduce</hl> will take the first two values of the list on the right hand side, assign them to
<hl>$a</hl> and <hl>$b</hl> respectively, execute the block.

Then it will take the result, assign it to <hl>$a</hl> and take the next element from the list,
assign it to <hl>$b</hl> and execute the block. This step will be repeated till the end of the list.

This code has two versions. The first one is more simple, but does not handle 0! properly.
The second works well for 0! as well.

0 comments on commit f06aa98

Please sign in to comment.