Skip to content

Instantly share code, notes, and snippets.

@MattOates
Last active December 19, 2015 08:39
Show Gist options
  • Save MattOates/5927162 to your computer and use it in GitHub Desktop.
Save MattOates/5927162 to your computer and use it in GitHub Desktop.
A Perl6 factorial function using a switch (given/when) statement and recursion.
sub factorial (Int $i) {
given $i {
when $i < 0 { fail "Not a Natural Number" }
when 0 { 1 }
when 1 { 1 }
default { $i * factorial $i-1 }
}
}
use Test;
isa_ok factorial(-1), Failure, "Factorial for -1 fails";
ok factorial(0) == 1, "Factorial for 0";
ok factorial(1) == 1, "Factorial for 1";
ok factorial(5) == 120, "Factorial for a larger integer";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment