Function definition: Difference between revisions

→‎{{header|Perl 6}}: show lambdas too
(→‎{{header|Perl 6}}: show lambdas too)
Line 745:
 
=={{header|Perl 6}}==
Without parametersa signature:
{{works with|Rakudo|#22 "Thousand Oaks"}}
 
Without parameters:
<lang perl6>sub multiply { return @_[0] * @_[1]; }</lang>
(Without an explicitThe return, ais subroutineoptional returnson the valuefinal ofstatement, since the last expression evaluatedwould return its value anyway. Also, theThe final semicolon in a block is also optional.)
(Beware that a subroutine without an explicit signature, like this one, magically becomes variadic (rather than nullary) only if <code>@_</code> or <code>%_</code> appear in the body.) In fact, we can define the variadic version explicitly, which still works for two arguments:
<lang perl6>sub multiply { [*] @_ }</lang>
 
With formal parameters and a return type:
<lang perl6>sub multiply (IntRat $a, IntRat $b --> IntRat) { $a * $b }</lang>
(Without an explicit return, a subroutine returns the value of the last expression evaluated. Also, the final semicolon in a block is optional.)
 
Same thing:
<lang perl6>sub multiply (IntRat $a, IntRat $b) returns IntRat { $a * $b }</lang>
my Rat sub multiply (Rat $a, Rat $b) { $a * $b }</lang>
 
It is possible to define a function in "lambda" notation and then bind that into a scope, in which case it works like any function:
 
<lang perl6>my &multiply := -> $a, $b { $a * $b };</lang>
 
NamingAnother theway functionto viawrite binding,a andlambda is with internal placeholder parameters:
 
<lang perl6>my &multiply := { $^a * $^b };</lang>
(And, in fact, our original <tt>@_</tt> above is just a variadic self-declaring placeholder argument. And the famous Perl "topic", <tt>$_</tt>, is just a self-declared parameter to a unary block.)
 
You may also curry both built-in and user-defined operators by supplying a <tt>*</tt> (known as "whatever") in place of the argument that is <i>not</i> to be curried:
Naming the function via binding, and with placeholder parameters:
<lang perl6>my &multiply := { $^a* * $^b }*;</lang>
This is not terribly readable in this case due to the visual confusion between the whatever star and the multiplication operator, but Perl knows when it's expecting terms instead of infixes, so only the middle star is multiplication.
It tends to work out much better with other operators. In particular, you may
curry a cascade of methods with only the original invocant missing:
<lang perl6>@list.grep( *.substr(0,1).lc.match(/<[0..9 a..f]>/) )</lang>
This is equivalent to:
<lang perl6>@list.grep( -> $obj { $obj.substr(0,1).lc.match(/<[0..9 a..f]>/) )</lang>
 
=={{header|PHP}}==
Anonymous user