Skip to content

Instantly share code, notes, and snippets.

@treyharris
Last active February 28, 2019 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyharris/507c511dd34b96a3df4b3dae51c0b94e to your computer and use it in GitHub Desktop.
Save treyharris/507c511dd34b96a3df4b3dae51c0b94e to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl6
use v6.c;
sub next-prime(Int $start = 1 --> Int) {
return ($start..*).grep({ .is-prime }).[1];
}
sub multiple(Int $multiplicand, Int $num = 1 --> Int) {
return $multiplicand * $num;
}
sub total(Int $addend, Int $num = 0 --> Int) {
return $addend + $num;
}
# This version fails when supplied just one argument:
sub MAIN-A(Int $num = 1, Int $operand?) {
put multiple($num, $operand);
put total($num, $operand);
put next-prime($num);
}
# with:
# Invocant of method 'Bridge' must be an object instance of type 'Int', not a type object of type 'Int'. Did you forget a '.new'?
# in sub multiple at ./args.p6 line 14
# in sub MAIN at ./args.p6 line 23
# in block <unit> at ./args.p6 line 22
#
# So, do we have to check the presence of the argument and call differently
# when it's absent, like so?:
sub MAIN-B(Int $num = 1, Int $operand?) {
if $operand {
put multiple($num, $operand);
put total($num, $operand);
put next-prime($num);
} else {
put multiple($num);
put total($num);
put next-prime($num);
}
}
# Or:
sub MAIN-C(Int $num = 1, Int $operand?) {
put $operand ?? multiple($num, $operand) !! multiple($num);
put $operand ?? total($num, $operand) !! total($num);
put next-prime($num);
}
# This doesn't work because unlike, say, Swift, you can't call positionals
# by name instead (and it might not work even if you could)
sub MAIN-D(Int $num = 1, Int $operand?) {
put multiple(:multiplicand($num), :num($operand));
put total(:addend($num), :operand($operand));
put next-prime(:start($num));
}
# Thanks to jnthn, this works:
sub MAIN(Int $num = 1, Int $operand?) {
put multiple(|($num || Empty, $operand || Empty));
put total(|($num || Empty, $operand || Empty));
put next-prime(|($num || Empty));
}
# But, is there a more idiomatic way?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment