Function prototype: Difference between revisions

Content added Content deleted
m (promoted to task)
Line 99: Line 99:


Other special forms are described in the User's Guide to the PARI library, section 5.7.3.
Other special forms are described in the User's Guide to the PARI library, section 5.7.3.
=={{header|Perl 6}}==
There is no restriction on placement of prototype declarations. (Actually, we call them "stub declarations".) In fact, stub declarations are rarely needed in Perl 6 because post-declaration of functions is allowed, and normal function declarations do not bend the syntax the way they sometimes do in Perl 5.

Note that the <tt>...</tt> in all of these stub bodies is literally part of the declaration syntax.

A prototype declaration for a function that does not require arguments (and returns an Int):
<lang perl6>sub foo ( --> Int) {...}</lang>

A prototype declaration for a function that requires two arguments.
Note that we can omit the variable name and just use the sigil in the stub, since we don't need to reference the argument until the actual definition of the routine. Also, unlike in Perl 5, a sigil like <tt>@</tt> defaults to binding a single positional argument.
<lang perl6>sub foo (@, $ --> Int) {...}</lang>

A prototype declaration for a function that utilizes varargs after one required argument.
Note the "slurpy" star turns the <tt>@</tt> sigil into a parameter that accepts all the rest of the positional arguments.
<lang perl6>sub foo ($, *@ --> Int) {...}</lang>

A prototype declaration for a function that utilizes optional arguments after one required argument. Optionality is conferred by either a question mark or a default:
<lang perl6>sub foo ($, $?, $ = 42 --> Int) {...}</lang>

A prototype declaration for a function that utilizes named parameters:
<lang perl6>sub foo ($, :$faster, :$cheaper --> Int) {...}</lang>

Example of prototype declarations for subroutines or procedures, which in Perl 6 is done simply by noting that nothing is returned:
<lang perl6>sub foo ($, $ --> Nil) {...}</lang>

A routine may also slurp up all the named arguments that were not bound earlier in the signature:
<lang perl6>sub foo ($, :$option, *% --> Int) {...}</lang>

A routine may make a named parameter mandatory using exclamation mark. (This is more useful in multi subs than in stubs though.)
<lang perl6>sub foo ($, :$option! --> Int) {...}</lang>


{{omit from|AutoHotkey}}
{{omit from|AutoHotkey}}