=begin pod

=TITLE Functions

=SUBTITLE Functions and Functional Programming in Perl 6

Routines are the smallest means of code reuse in Perl 6. They come in several
forms, most notably methods, which belong in classes and roles and are
associated with an object, and functions, also called I<subroutines> or short
I<sub>s, which exist independently of objects.

Subroutines default to lexical (C<my>) scoping, and calls to them are
generally resolved at compile time.

Subroutines can have a L<signature|/type/Signature>, also called I<parameter
list>, which specifies which, if any, arguments the signature expects. It can
specify (or leave open) both the number and types of arguments, and also the
return value.

=head1 Defining/Creating/Using Functions

=head2 X<Subroutines|declarator,sub>

To create a function, often all that's needed is to define a
subroutine using the C<sub> declarator:

    sub my-func { say "Look ma, no args!" }
    my-func;

To have the subroutine take arguments, a L<signature|Signature> goes
between the subroutine's name and its body, in parentheses:

=for code :allow<B L>
sub exclaim B<($phrase)> {
    say $phrase L<~> "!!!!"
}
exclaim "Howdy, World";

By default, subroutines are L<lexically scoped|/syntax/my>. That is
C<sub foo {...}> is the same as C<my sub foo {...}> and is only
defined within the current scope.

=begin code :allow<L>
sub escape ($str) {
    L<$_> = $str;
    # Puts a slash before non-alphanumeric characters
    L<s>:g[<-alpha-digit>] = "\\$/";
}

say escape "foo#bar?" # foo\#bar\?

{
    sub escape ($str) {
        $_ = $str;
        # Writes each non-alphanumeric character in its hexadecimal escape
        s:g|<-alpha-digit>| = "\\x[{ $/.base(16) }]";
    }

    say escape "foo#bar?" # foo\x[23]bar\x[3F]
}

# Back to original escape function
say escape "foo#bar?" # foo\#bar\?
=end code

Subroutines don't have to be named; in this case they're called anonymous.

    say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # 25

But in this case, it's often desirable to use the more succinct L<block|Block>
syntax. Subroutines and blocks can be called in place, as in the example above.

=head2 X«Blocks and Lambdas|syntax,->»

Whenever you see something like C«{ $_ + 42 }»,
C«-> $a, $b { $a ** $b }», or C«{ $^text.indent($:spaces) }», that's
L<Block> syntax. It's used after every C<if>, C<for>, C<while>, etc.

    for 1, 2, 3, 4 -> $a, $b {
        say $a ~ $b;
    }

    12
    34

They can also be used on their own as anonymous blocks of code.

    say { $^a ** 2 + $^b ** 2}(3, 4) # 25

For details about the syntax of blocks, see the documentation for the
L<Block> type.

=head2 Signatures

The parameters that a function accepts are described in its I<signature>.

=for code :allow<B>
sub formatB<(Str $s)> { ... }
-> B<$a, $b> { ... }

Details about the syntax and use of signatures can be found in the
L<documentation on the C<Signature> class|Signature>.

=comment capture, destructuring,

=head2 Arguments

Arguments are supplied as a comma separated list. To disambiguate nested calls
parentheses or adverbial form can be used.

    sub f(&c){ c() * 2 }; # call the function reference c with empty parameter list
    sub g($p){ $p - 2 };
    say(g(42)); # nest call to g in call to say
    f: { say g(666) }; # call f with a block

When calling a function, positional arguments should be supplied
in the same order as the function's signature.  Named arguments
may be supplied in any order, but it is considered good form to
place named arguments after positional arguments.  Inside the
argument list of a function call, some special syntax is supported:

    f :named(35)     # A named argument (in "adverb" form.)
    f named => 35    # Also a named argument.
    f :35named       # A named argument using abbreviated adverb form
    f 'named' => 35  # Not a named argument, a Pair in a positional argument
    f |$c            # Merge the contents of Capture $c as if they were supplied

Arguments passed to a function are conceptually first collected in a
C<Capture> container.  Details about the syntax and use of these
containers can be found in the L<documentation on the C<Capture> class|Capture>.

When using named arguments, note that normal List "pair-chaining" allows
one to skip commas between named arguments.

    f :dest</tmp/foo> :src</tmp/bar> :lines(512)
    f :32x :50y :110z   # This flavor of "adverb" works, too
    f :a:b:c            # The spaces are also optional.

=head2 X<Multi-dispatch|declarator,multi>

Perl 6 allows you to write several routines with the same name, but different
signatures. When the routine is called by name, the runtime environment
decides which is the best match, and calls that I<candidate>. You declare
each candidate with the C<multi> declarator.

    multi congratulate($name) {
        say "Happy birthday, $name";
    }
    multi congratulate($name, $age) {
        say "Happy {$age}th birthday, $name";
    }

    congratulate 'Larry';       # Happy birthday, Larry
    congratulate 'Bob', 45;     # Happy 45th birthday, Bob

Dispatch can happen on the number of arguments (the I<arity>), but also on the
type:

    multi as-json(Bool $d) { $d ?? 'true' !! 'false'; }
    multi as-json(Real $d) { ~$d }
    multi as-json(@d)      { sprintf '[%s]', @d.map(&as-json).join(', ') }

    say as-json([True, 42]);    # [true, 42]

C<multi> without any specific routine type always defaults to a C<sub>, but you
can use it on methods as well. The candidates are all the multi methods of the
object:

    class Congrats {
        multi method congratulate($reason,$name) {
            say "Hooray for your $reason, $name";
        }
    }

    role BirthdayCongrats {
        multi method congratulate('birthday',$name) {
            say "Happy birthday, $name";
        }
        multi method congratulate('birthday',$name,$age) {
            say "Happy {$age}th birthday, $name";
        }
    }

    my $congrats = Congrats.new does BirthdayCongrats;

    $congrats.congratulate('promotion','Cindy'); #-> Hooray for your promotion, Cindy
    $congrats.congratulate('birthday','Bob');    #-> Happy birthday, Bob

=head3 X<proto|declarator>

C<proto> is a way to formally declare commonalities between C<multi>
candidates. It acts as a wrapper that can validate but not modify
arguments. Consider this basic example:

    proto congratulate(Str $reason, Str $name, |) {*}
    multi congratulate($reason, $name) {
       say "Hooray for your $reason, $name";
    }
    multi congratulate($reason, $name, Int $rank) {
       say "Hooray for your $reason, $name -- you got rank $rank!";
    }

    congratulate('being a cool number', 'Fred');     # OK
    congratulate('being a cool number', 'Fred', 42); # OK
    congratulate('being a cool number', 42);         # Proto match error

All C<multi congratulate> will conform to the basic signature of two strings,
optionally followed by further parameters. The C<|> is an un-named C<Capture>
parameter, allowing a C<multi> which takes additional arguments. The third call
fails at compile time because the proto's C<signature> becomes the common
signature of all three, and C<42> doesn't match C<Str>.

    say &congratulate.signature #-> (Str $reason, Str $name, | is raw)

You can give the C<proto> a function body, and place the C<{*}> where
you want the dispatch to be done.

    # attempts to notify someone -- returns False if unsuccessful
    proto notify(Str $user,Str $msg) {
       my \hour = DateTime.now.hour;
       if hour > 8 or hour < 22 {
          return {*};
       } else {
          # we can't notify someone when they might be sleeping
          return False;
       }
    }

C<{*}> always dispatches to candidates with the parameters it's called
with. Parameter defaults and type coercions will work but are not be passed on.

    proto mistake-proto(Str() $str, Int $number = 42) {*}
    multi mistake-proto($str,$number) { say $str.WHAT }
    mistake-proto(7,42);   #-> (Int) -- coercions not passed on
    mistake-proto('test'); #!> fails -- defaults not passed on

=comment only

=head1 Conventions and Idioms

While the dispatch system described above provides a lot of flexibility,
there are some conventions that most internal functions, and those in
many modules, will follow.  These produce a consistent look and feel.

=head2 Slurpy Conventions

Perhaps the most important of these is the way slurpy list arguments are
handled.  Most of the time, functions will not automatically flatten
slurpy lists.  The rare exceptions are those functions that don't have a
reasonable behavior on lists of lists, for example, L<chrs|routine/chrs>,
or where there is a conflict with an established idiom, like L<pop|routine/pop>
being the inverse of C<push|routine/push>.

If you wish to match this look and feel, any Iterable argument must
be broken out element-by-element using a **@ slurpy, with two nuances:

=item An Iterable inside a L<Scalar container|containers#Scalar_containers|> does not count.
=item Lists created with a L<C<,>|routine/,> at the top level only count as one Iterable.

This can be achieved by using a slurpy with a C<+> or C<+@> instead of C<**>:

    sub grab (+@a) { "grab $_".say for @a }

...which is shorthand for something very close to:

    multi sub grab (**@a) { "grab $_".say for @a }
    multi sub grab (\a) {
        a ~~ Iterable and a.VAR !~~ Scalar ?? nextwith(|a) !! nextwith(a,)
    }

This results in the following behavior, which is known as the "single
argument rule" and is important to understand when invoking slurpy functions:

    grab(1,2);     # grab 1 grab 2
    grab((1,2));   # grab 1 grab 2
    grab($(1,2));  # grab 1 2
    grab((1,2),3); # grab 1 2 grab 3

This also makes user-requested flattening feel consistent whether there is
one sublist, or many:

    grab(flat (1,2),(3,4));   # grab 1 grab 2 grab 3 grab 4
    grab(flat $(1,2),$(3,4)); # grab 1 2 grab 3 4
    grab(flat (1,2));         # grab 1 grab 2
    grab(flat $(1,2));        # grab 1 2

It is worth noting that mixing binding and sigilless variables
in these cases requires a bit of finesse, because there is no Scalar
intermediary used during binding.

    my $a = (1,2);  # Normal assignment, equivalent to $(1,2)
    grab ($a);      # grab 1 2
    my $b := (1,2); # Binding, $b links directly to a bare (1,2)
    grab ($b);      # grab 1 grab 2
    my \c = (1,2);  # Sigilless variables always bind, even with '='
    grab (c);       # grab 1 grab 2

=head1 Functions are First-Class Objects

Functions and other code objects can be passed around as values, just like any
other object.

There are several ways to get hold of a code object. You can assign it to a
variable at the point of declaration:

=begin code
my $square = sub (Numeric $x) { $x * $x }
# and then use it:
say $square(6);    # 36
=end code

Or you can reference an existing named function by using the C<&> in front of
it.

=begin code
sub square ($x) { $x * $x };

# get hold of a reference to the function:
my $func = &square
=end code

This is very useful for I<higher order functions>, that is, functions that
take other functions as input. A simple one is L<map|/type/List#routine_map>,
which applies a function to each input element:

    sub square ($x) { $x * $x };
    my @squared = map &square,  1..5;
    say join ', ', @squared;        # 1, 4, 9, 16, 25


=head2 Closures

All code objects in Perl 6 are I<closures>, which means they can reference
lexical variables from an outer scope.

=begin code
sub generate-sub($x) {
    my $y = 2 * $x;
    return sub { say $y };
    #      ^^^^^^^^^^^^^^  inner sub, uses $y
}
my $generated = generate-sub(21);
$generated();           # 42
=end code

Here C<$y> is a lexical variable inside C<generate-sub>, and the inner
subroutine that is returned uses it. By the time that the inner sub is called,
C<generate-sub> has already exited. Yet the inner sub can still use C<$y>,
because it I<closed> over the variable.

A less obvious but useful example for closures is using L<map|/type/List#routine_map>
to multiply a list of numbers:

    my $multiply-by = 5;
    say join ', ', map { $_ * $multiply-by }, 1..5;     # 5, 10, 15, 20, 25

Here the block passed to C<map> references the variable C<$multiply-by> from
the outer scope, making the block a closure.

Languages without closures cannot easily provide higher-order functions that
are as easy to use and powerful as C<map>.

=head2 Routines

Routines are code objects that conform to L<type Routine|/type/Routine>, most
notably L<Sub|/type/Sub>, L<Method|/type/Method>, L<Regex|/type/Regex> and
L<Submethod|/type/Submethod>.

They carry additional functionality in addition to what L<Block|/type/Block>
supplies: they can come as L<multis|#Multi-dispatch>,
you can L<wrap|/type/Routine#method wrap> them, and exit early with C<return>:

=begin code :allow<B>
my $keywords = set <if for unless while>;

sub has-keyword(*@words) {
    for @words -> $word {
        B<return> True if $word (elem) $keywords;
    }
    False;
}

say has-keyword 'not', 'one', 'here';       # False
say has-keyword 'but', 'here', 'for';       # True
=end code

Here C<return> does not just leave the block inside which it was called, but
the whole routine. In general, blocks are transparent to C<return>, they
attach to the outer routine.


=comment Important ones: candidates, wrap, unwrap, assuming, arity, count

=head1 Defining Operators

Operators are just subroutines with funny names. The funny names are composed
of the category name (C<infix>, C<prefix>, C<postfix>, C<circumfix>,
C<postcircumfix>), followed by a colon, and a list of the operator name or
names (two components in the case of circumfix and postcircumfix).

This works both for adding multi candidates to existing operators, and for
defining new ones. In the latter case, the definition of the new subroutine
automatically installs the new operator into the grammar, but only in the
current lexical scope. Importing an operator via C<use> or C<import> also
makes it available.

=begin code
# adding a multi candidate to an existing operator:
multi infix:<+>(Int $x, "same") { 2 * $x };
say 21 + "same",            # 42

# defining a new operator
sub postfix:<!>(Int $x where { $x >= 0 }) { [*] 1..$x };
say 6!;                     # 720
=end code

The operator declaration becomes available as soon as possible, so you can
even recurse into a just-defined operator, if you really want to:

=begin code
sub postfix:<!>(Int $x where { $x >= 0 }) {
    $x == 0 ?? 1 !! $x * ($x - 1)!
}
say 6!;                     # 720
=end code

Circumfix and postcircumfix operators are made of two delimiters, one opening
and one closing.

=begin code
sub circumfix:<START END>(*@elems) {
    "start", @elems, "end"
}

say START 'a', 'b', 'c' END;        # start a b c end
=end code

Postcircumfixes also receive the term after which they are parsed as
an argument:

=begin code
sub postcircumfix:<!! !!>($left, $inside) {
    "$left -> ( $inside )"
}
say 42!! 1 !!;      # 42 -> ( 1 )
=end code

=head2 Precedence

Operator precedence in Perl 6 is specified relatively to existing operators.
With C<is tighter(&other-operator)> you can squeeze in an operator with a
tighter precedence than the one you specified, but looser than the
next-tighter precedence level.

For example C<< infix:<*> >> has a tighter precedence than C<< infix:<+> >>,
and squeezing one in between works like this:

=begin code
sub infix:<!!>($a, $b) is tighter(&infix:<+>) {
    2 * ($a + $b)
}

say 1 + 2 * 3 !! 4;     # 29
=end code

Here the C<1 + 2 * 3 !! 4> is parsed as C<1 + ((2 * 3) !! 4)>, because the
precedence of the new C<!!> operator is between that of C<+> and C<*>.

The same effect could have been achieved with

    sub infix:<!!>($a, $b) is looser(&infix:<*>) { ... }

To put a new operator on the same precedence level as an existing operator,
use C<is equiv(&other-operator)> instead.


=head2 Associativity

When the same operator appears several times in a row, there are multiple
possible interpretations. For example

    1 + 2 + 3

could be parsed as

    (1 + 2) + 3         # left associative

or as

    1 + (2 + 3)         # right associative

or as single call to an operator with three operands

    infix:<+>(1, 2, 3); # list associative

For addition of real numbers, the distinction is somewhat moot, because C<+> is
L<mathematically associative|https://en.wikipedia.org/wiki/Associative_property>.

But for other operators it matters a great deal. For example for the
exponentiation/power operator, C<< infix:<**> >>:

    say 2 ** (2 ** 3);      # 256
    say (2 ** 2) ** 3;      # 64

Perl 6 has the following possible associativity configurations:

=begin table

    A   Assoc     Meaning of $a ! $b ! $c
    =   =====     =======================
    L   left      ($a ! $b) ! $c
    R   right     $a ! ($b ! $c)
    N   non       ILLEGAL
    C   chain     ($a ! $b) and ($b ! $c)
    X   list      infix:<!>($a; $b; $c)

=end table

You can specify the associativity of an operator with the C<is assoc> trait,
where C<left> is the default associativity.

=begin code
sub infix:<§>(*@a) is assoc<list> {
    '(' ~ @a.join('|') ~ ')';
}

say 1 § 2 § 3;      # (1|2|3)
=end code

=head1 Traits

I<Traits> are subroutines that are run at compile time to modify the behavior of a
type, variable, routine, attribute, or other language object.

Examples of traits are:

    class ChildClass is ParentClass { ... }
    #                ^^ trait, with argument ParentClass
    has $.attrib is rw;
    #            ^^^^^  trait with name 'rw'
    class SomeClass does AnotherRole { ... }
    #               ^^^^ trait
    has $!another-attribute handles <close>;
    #                       ^^^^^^^ trait

... and also C<is tighter>, C<is looser>, C<is equiv> and C<is assoc> from the previous
section.

Traits are subs of the form C<< trait_mod<VERB> >>, where C<VERB> stands for the
name like C<is>, C<does> or C<handles>. It receives the modified thing as
argument, and the name as a named argument.

=begin code
multi sub trait_mod:<is>(Routine $r, :$doubles!) {
    $r.wrap({
        2 * callsame;
    });
}

sub square($x) is doubles {
    $x * $x;
}

say square 3;       # 18
=end code

See L<type Routine|/type/Routine> for the documentation of built-in routine
traits.

=head1 Re-dispatching

There are cases in which a routine might want to call the next method
from a chain. This chain could be a list of parent classes in a class
hierarchy, or it could be less specific multi candidates from a multi
dispatch, or it could be the inner routine from a C<wrap>.

In all those cases, you can use C<callwith> to call the next routine in the
chain with arguments of your own choice.

For example

=begin code
multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    my $res = callwith($x + 1);
    say "Back in Int with $res";
}

a 1;
=end code

produces this output:

=begin code
Int 1
Any 2
Back in Int with 5
=end code

Here C<a 1> calls the most specific C<Int> candidate first, and C<callwith>
re-dispatches to the less specific C<Any> candidate.

Very often, a re-dispatch passes the same argument along that the caller
received, so there is a special routine for that: C<callsame>.

=begin code
multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    my $res = callsame;
    say "Back in Int with $res";
}

a 1;        # Int 1\n Any 1\n Back in Int with 5
=end code

Another common use case is to re-dispatch to the next routine in the chain,
and not do anything else afterwards. That's why we have C<nextwith> and
C<nextsame>, which call the next routine with arbitrary arguments
(C<nextwith>) or with the same argument as the caller received (C<nextsame>),
but never return to the caller. Or to phrase it differently, the C<nextsame>
and C<nextwith> variants replace the current callframe with the next
candidate.

=begin code
multi a(Any $x) {
    say "Any $x";
    return 5;
}
multi a(Int $x) {
    say "Int $x";
    nextsame;
    say "back in a";    # never executed, because 'nextsame' doesn't return
}

a 1;        # Int 1\n Any 1
=end code

As mentioned earlier, multi subs are not the only situation in which
X<C<callwith>|callwith>, X<C<callsame>|callsame>, X<C<nextwith>|nextwith> and X<C<nextsame>|nextsame> can be helpful.
One is is for dispatching to wrapped routines:

=begin code
# enable wrapping:
use soft;

# function to be wrapped:
sub square-root($x) { $x.sqrt }

&square-root.wrap(-> $num {
   nextsame if $num >= 0;
   1i * callwith(abs($num));
});

say square-root(4);     # 2
say square-root(-4);    # 0+2i
=end code

The final use case is to re-dispatch to methods from parent classes.

=begin code
class LoggedVersion is Version {
    method new(|c) {
        note "New version object created with arguments " ~ c.perl;
        nextsame;
    }
}

say LoggedVersion.new('1.0.2');
=end code

=head1 Coercion Types

Coercion types can help you to have a specific type inside a routine, but
accept wider input. When the routine is called, the argument is automatically
converted to the narrower type.

=begin code
sub double(Int(Cool) $x) {
    2 * $x
}

say double '21';    # 42
say double Any;     # Type check failed in binding $x; expected 'Cool' but got 'Any'
=end code

Here the C<Int> is the target type to which the argument will be coerced, and
C<Cool> is the type that the routine accepts as input.

If the accepted input type is L<Any|/type/Any>, you can abbreviate C<Int(Any)>
to C<Int()>.

The coercion works simply by looking for a method with the same name
as the target type. So you can define coercions for your own types like so:

    class MyModule::Foo {
       has $.msg = "I'm a foo!";

       method MyModule::Bar {
          ::('MyModule::Bar').new(:msg($.msg ~ ' But I am now Bar.'));
       }
    }

    class MyModule::Bar {
       has $.msg;
    }

    sub print-bar(MyModule::Bar() $bar) {
       say $bar.WHAT; #MyModule::Bar
       say $bar.msg;  #I'm a foo! But I am now Bar.
    }

    print-bar MyModule::Foo.new;

Coercion types are supposed to work wherever types work, but Rakudo
currently (2015.02) only implements them for subroutine parameters.

=head1 C<sub MAIN>

The sub with the special name C<MAIN> is executed after all relevant phaser
and it's signature is the means by which command line arguments can be parsed.
Multi methods are supported and a usage method is automatically generated and
displayed if no command line arguments are provided.

    sub MAIN ( Int :$length = 24, :file($data) = 'file.dat', Bool :$verbose ) {
        say $length if $length.defined;
        say $data   if $data.defined;
        say 'Verbosity ', ($verbose ?? 'on' !! 'off');
    }

=end pod

# vim: expandtab shiftwidth=4 ft=perl6
