Last active
December 19, 2015 08:39
-
-
Save MattOates/5927162 to your computer and use it in GitHub Desktop.
A Perl6 factorial function using a switch (given/when) statement and recursion.
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
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