txt: ## functions.md
  ## Chunk 2 of 2
  raku
  sub testee(Int $i, Str $s){
      rand.Rat * $i ~ $s;
  }
  
  sub wrap-to-debug(&c){
      say "wrapping {&c.name} with arguments {&c.signature.raku}";
      &c.wrap: sub (|args){
          note "calling {&c.name} with {args.gist}";
          my \ret-val := callwith(|args);
          note "returned from {&c.name} with return value {ret-val.raku}";
          ret-val
      }
  }
  
  my $testee-handler = wrap-to-debug(&testee);
  # OUTPUT: «wrapping testee with arguments :(Int $i, Str $s)␤»
  
  say testee(10, "ten");
  # OUTPUT: «calling testee with \(10, "ten")␤returned from testee with return value "6.151190ten"␤6.151190ten␤»
  &testee.unwrap($testee-handler);
  say testee(10, "ten");
  # OUTPUT: «6.151190ten␤»
  ```
  
  # [Defining operators](#Functions "go to top of document")[§](#Defining_operators "direct link")
  
  Operators are just subroutines with funny names. The funny names are composed of the category name (`infix`, `prefix`, `postfix`, `circumfix`, `postcircumfix`), followed by a colon, and a list of the operator name or names (two components in the case of circumfix and postcircumfix). An expanded explanation of all these operators and what they mean is included [in this table](/language/operators#Operator_classification).
  
  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 `use` or `import` also makes it available.
  
  ```raku
  # adding a multi candidate to an existing operator:
  multi infix:<+>(Int $x, "same") { 2 * $x };
  say 21 + "same";            # OUTPUT: «42␤»
  
  # defining a new operator
  sub postfix:<!>(Int $x where { $x >= 0 }) { [*] 1..$x };
  say 6!;                     # OUTPUT: «720␤»
  
  ```
  
  The operator declaration becomes available as soon as possible, so you can recurse into a just-defined operator:
  
  ```raku
  sub postfix:<!>(Int $x where { $x >= 0 }) {
      $x == 0 ?? 1 !! $x * ($x - 1)!
  }
  say 6!;                     # OUTPUT: «720␤»
  
  ```
  
  Circumfix and postcircumfix operators are made of two delimiters, one opening and one closing.
  
  ```raku
  sub circumfix:<START END>(*@elems) {
      "start", @elems, "end"
  }
  
  say START 'a', 'b', 'c' END;        # OUTPUT: «(start [a b c] end)␤»
  
  ```
  
  Postcircumfixes also receive the term after which they are parsed as an argument:
  
  ```raku
  sub postcircumfix:<!! !!>($left, $inside) {
      "$left -> ( $inside )"
  }
  say 42!! 1 !!;      # OUTPUT: «42 -> ( 1 )␤»
  
  ```
  
  Blocks can be assigned directly to operator names. Use a variable declarator and prefix the operator name with an `&`-sigil.
  
  ```raku
  my &infix:<ieq> = -> |l { [eq] l>>.fc };
  say "abc" ieq "Abc";
  # OUTPUT: «True␤»
  ```
  
  ## [Precedence](#Functions "go to top of document")[§](#Precedence "direct link")
  
  Operator precedence in Raku is specified relative to existing operators. The traits `is tighter`, `is equiv` and `is looser` can be provided with an operator to indicate how the precedence of the new operator is related to other, existing ones. More than one trait can be applied.
  
  For example, `infix:<*>` has a tighter precedence than `infix:<+>`, and squeezing one in between works like this:
  
  ```raku
  sub infix:<!!>($a, $b) is tighter(&infix:<+>) {
      2 * ($a + $b)
  }
  
  say 1 + 2 * 3 !! 4;     # OUTPUT: «21␤»
  
  ```
  
  Here, the `1 + 2 * 3 !! 4` is parsed as `1 + ((2 * 3) !! 4)`, because the precedence of the new `!!` operator is between that of `+` and `*`.
  
  The same effect could have been achieved with:
  
  ```raku
  sub infix:<!!>($a, $b) is looser(&infix:<*>) { ... }
  ```
  
  To put a new operator on the same precedence level as an existing operator, use `is equiv(&other-operator)` instead.
  
  ## [Associativity](#Functions "go to top of document")[§](#Associativity "direct link")
  
  When the same operator appears several times in a row, there are multiple possible interpretations. For example:
  
  ```raku
  1 + 2 + 3
  ```
  
  could be parsed as
  
  ```raku
  (1 + 2) + 3         # left associative
  ```
  
  or as
  
  ```raku
  1 + (2 + 3)         # right associative
  ```
  
  For addition of real numbers, the distinction is somewhat moot, because `+` is [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, `infix:<**>`:
  
  ```raku
  say 2 ** (2 ** 3);      # OUTPUT: «256␤»
  say (2 ** 2) ** 3;      # OUTPUT: «64␤»
  ```
  
  Raku has the following possible associativity configurations:
  
  | Associativity | Meaning of $a ! $b ! $c |
  | --- | --- |
  | left | ($a ! $b) ! $c |
  | right | $a ! ($b ! $c) |
  | non | ILLEGAL |
  | chain | ($a ! $b) and ($b ! $c) |
  | list | infix:<!>($a; $b; $c) |
  
  The [Operator docs](/language/operators#Operator_associativity) contain additional details about operator associativity.
  
  You can specify the associativity of an infix operator with the `is assoc` trait, where `left` is the default associativity. Specifying the associativity of non-infix operators is planed but not yet implemented.
  
  ```raku
  sub infix:<§>(*@a) is assoc<list> {
      '(' ~ @a.join('|') ~ ')';
  }
  
  say 1 § 2 § 3;      # OUTPUT: «(1|2|3)␤»
  
  ```
  
  # [Traits](#Functions "go to top of document")[§](#Traits "direct link")
  
  *Traits* are subroutines that run at compile time and modify the behavior of a type, variable, routine, attribute, or other language object.
  
  Examples of traits are:
  
  ```raku
  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 `is tighter`, `is looser`, `is equiv` and `is assoc` from the previous section.
  
  Traits are subs declared in the form `trait_mod<VERB>`, where `VERB` stands for the name like `is`, `does` or `handles`. It receives the modified thing as argument, and the name as a named argument. See [`Sub`](/type/Sub#Traits) for details.
  
  ```raku
  multi trait_mod:<is>(Routine $r, :$doubles!) {
      $r.wrap({
          2 * callsame;
      });
  }
  
  sub square($x) is doubles {
      $x * $x;
  }
  
  say square 3;       # OUTPUT: «18␤»
  
  ```
  
  See [type Routine](/type/Routine) for the documentation of built-in routine traits.
  
  # [Re-dispatching](#Functions "go to top of document")[§](#Re-dispatching "direct link")
  
  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 `wrap`.
  
  Fortunately, we have a series of re-dispatching tools that help us to make it easy.
  
  ## [The Next Tools](#Functions "go to top of document")[§](#The_Next_Tools "direct link")
  
  The table below represents the next tools in relation to three attributes:
  
  * **Returns:** "Yes" means that it returns, and the code will continue from that point. "No" means that it never returns to this function -- it's as though the call has a built-in "return".
  * **Arguments:** Specifically, whether the arguments from the current function are reused in the call, or whether you need to specify some arguments. In the case of `nextcallee`, there are no arguments needed, because they're instead passed to the return value when it's called.
  * **Referee:** This is the method that will be called by the tool (the reciprocal of "referrer"). It can be one of:
  
  * **next:** The next item in the chain
  * **self:** It will call itself again, as in recursion
  * **preset:** It will call the item that was saved by `nextcallee`
  
  |  | Returns | Arguments | Referee\* |
  | --- | --- | --- | --- |
  | nextsame | No | Reuse | next |
  | nextwith | No | Specify | next |
  | callsame | Yes | Reuse | next |
  | callwith | Yes | Specify | next |
  | nextcallee | Yes | None | next |
  | samewith | Yes | Specify | self |
  | nextcallee's rv\* | Yes | Specify | preset |
  
  \* `nextcallee`'s rv is the tool returned from calling `nextcallee`, which itself can be called.
  
  From the above we learn:
  
  * `with` always means that the arguments need to be specified -- this one is consistent.
  * `same` at word end means the arguments of the currently running function will automatically be reused when calling the referee. Note that `samewith`, despite containing "same", doesn't mean that the arguments will be reused. That's because the "same" here refers to the Referee -- the function is calling the same method as itself, not the next in the call stack.
  * `next` means that it won't return, except for `nextcallee`, which does return
  
  ## [sub callsame](#Functions "go to top of document")[§](#sub_callsame "direct link")
  
  `callsame` calls the next matching candidate with the same arguments that were used for the current candidate and returns that candidate's return value.
  
  ```raku
  proto a(|) {*}
  
  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;        # OUTPUT: «Int 1␤Any 1␤Back in Int with 5␤»
  
  ```
  
  ## [sub callwith](#Functions "go to top of document")[§](#sub_callwith "direct link")
  
  `callwith` calls the next candidate matching the original signature, that is, the next function that could possibly be used with the arguments provided by users and returns that candidate's return value.
  
  ```raku
  proto a(|) {*}
  
  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;        # OUTPUT: «Int 1␤Any 2␤Back in Int with 5␤»
  
  ```
  
  Here, `a 1` calls the most specific [`Int`](/type/Int) candidate first, and `callwith` re-dispatches to the less specific [`Any`](/type/Any) candidate. Note that although our parameter `$x + 1` is an [`Int`](/type/Int), still we call the next candidate in the chain.
  
  In this case, for example:
  
  ```raku
  proto how-many(|) {*}
  
  multi how-many( Associative $a ) {
      say "Associative $a ";
      my $calling = callwith( 1 => $a );
      return $calling;
  }
  
  multi how-many( Pair $a ) {
      say "Pair $a ";
      return "There is $a "
  
  }
  
  multi how-many( Hash $a ) {
      say "Hash $a";
      return "Hashing $a";
  }
  
  my $little-piggy = little => 'piggy';
  say $little-piggy.^name;        # OUTPUT: «Pair␤»
  say &how-many.cando( \( $little-piggy ));
  # OUTPUT: «(sub how-many (Pair $a) { #`(Sub|68970512) ... } sub how-many (Associative $a) { #`(Sub|68970664) ... })␤»
  say how-many( $little-piggy  ); # OUTPUT: «Pair little     piggy␤There is little piggy␤»
  
  ```
  
  the only candidates that take the [`Pair`](/type/Pair) argument supplied by the user are the two functions defined first. Although a [`Pair`](/type/Pair) can be easily coerced to a [`Hash`](/type/Hash), here is how signatures match:
  
  ```raku
  say :( Pair ) ~~ :( Associative ); # OUTPUT: «True␤»
  say :( Pair ) ~~ :( Hash );        # OUTPUT: «False␤»
  
  ```
  
  The arguments provided by us are a [`Pair`](/type/Pair). It does not match a [`Hash`](/type/Hash), so the corresponding function is thus not included in the list of candidates, as can be seen by the output of `&how-many.cando( \( $little-piggy ));`.
  
  ## [sub nextsame](#Functions "go to top of document")[§](#sub_nextsame "direct link")
  
  `nextsame` calls the next matching candidate with the same arguments that were used for the current candidate and **never** returns.
  
  ```raku
  proto a(|) {*}
  
  multi a(Any $x) {
      say "Any $x";
      return 5;
  }
  multi a(Int $x) {
      say "Int $x";
      nextsame;
      say "never executed because nextsame doesn't return";
  }
  
  a 1;        # OUTPUT: «Int 1␤Any 1␤»
  
  ```
  
  ## [sub nextwith](#Functions "go to top of document")[§](#sub_nextwith "direct link")
  
  `nextwith` calls the next matching candidate with arguments provided by users and **never** returns.
  
  ```raku
  proto a(|) {*}
  
  multi a(Any $x) {
      say "Any $x";
      return 5;
  }
  multi a(Int $x) {
      say "Int $x";
      nextwith($x + 1);
      say "never executed because nextwith doesn't return";
  }
  
  a 1;        # OUTPUT: «Int 1␤Any 2␤»
  
  ```
  
  ## [sub samewith](#Functions "go to top of document")[§](#sub_samewith "direct link")
  
  `samewith` calls the multi again with arguments provided at the call site and returns the value provided by the call. This can be used for self-recursion.
  
  ```raku
  proto factorial(|) {*}
  
  multi factorial(Int $x where * ≤ 1) { 1 }
  multi factorial(Int $x) {
      $x * samewith($x-1);
  }
  
  say (factorial 10); # OUTPUT: «36288000␤»
  
  ```
  
  ## [sub nextcallee](#Functions "go to top of document")[§](#sub_nextcallee "direct link")
  
  Redispatch may be required to call a block that is not the current scope what provides `nextwith` and friends with the problem to referring to the wrong scope. Use `nextcallee` to capture the right candidate and call it at the desired time.
  
  ```raku
  proto pick-winner(|) {*}
  
  multi pick-winner (Int \s) {
      my &nextone = nextcallee;
      Promise.in(π²).then: { nextone s }
  }
  multi pick-winner { say "Woot! $^w won" }
  
  with pick-winner ^5 .pick -> \result {
      say "And the winner is...";
      await result;
  }
  
  # OUTPUT:
  # And the winner is...
  # Woot! 3 won
  
  ```
  
  The [`Int`](/type/Int) candidate takes the `nextcallee` and then fires up a [`Promise`](/type/Promise) to be executed in parallel, after some timeout, and then returns. We can't use `nextsame` here, because it'd be trying to `nextsame` the Promise's block instead of our original routine.
  
  Note that, despite its name, the `nextcallee` function is like:
  
  * `callwith`/`nextwith`, in that it takes parameters
  * `callwith`/`callsame`, in that it returns; the call to `nextcallee` returns a reference, and the call to the reference also returns (unlike `nextwith`/`nextsame`, which don't return)
  
  ## [Wrapped routines](#Functions "go to top of document")[§](#Wrapped_routines "direct link")
  
  Besides those already mentioned above, re-dispatch is helpful in many more situations. For instance, for dispatching to wrapped routines:
  
  ```raku
  # enable wrapping:
  use soft;
  
  # function to be wrapped:
  sub square-root($x) { $x.sqrt }
  
  &square-root.wrap(sub ($num) {
     nextsame if $num >= 0;
     1i * callwith(abs($num));
  });
  
  say square-root(4);     # OUTPUT: «2␤»
  say square-root(-4);    # OUTPUT: «0+2i␤»
  
  ```
  
  ## [Routines of parent class](#Functions "go to top of document")[§](#Routines_of_parent_class "direct link")
  
  Another use case is to re-dispatch to methods from parent classes.
  
  ```raku
  say Version.new('1.0.2') # OUTPUT: v1.0.2
  
  ```
  
  ```raku
  class LoggedVersion is Version {
      method new(|c) {
          note "New version object created with arguments " ~ c.raku;
          nextsame;
      }
  }
  
  say LoggedVersion.new('1.0.2');
  
  # OUTPUT:
  # New version object created with arguments \("1.0.2")
  # v1.0.2
  
  ```
  
  # [Coercion types](#Functions "go to top of document")[§](#Coercion_types "direct link")
  
  Coercion types force a specific type for routine arguments while allowing the routine itself to accept a wider input. When invoked, the arguments are narrowed automatically to the stricter type, and therefore within the routine the arguments have always the desired type.
  
  In the case the arguments cannot be converted to the stricter type, a *Type Check* error is thrown.
  
  ```raku
  sub double(Int(Cool) $x) {
      2 * $x
  }
  
  say double '21';# OUTPUT: «42␤»
  say double  21; # OUTPUT: «42␤»
  say double Any; # Type check failed in binding $x; expected 'Cool' but got 'Any'
  
  ```
  
  In the above example, the [`Int`](/type/Int) is the target type to which the argument `$x` will be coerced, and [`Cool`](/type/Cool) is the type that the routine accepts as wider input.
  
  If the accepted wider input type is [`Any`](/type/Any), it is possible to abbreviate the coercion `Int(Any)` by omitting the [`Any`](/type/Any) type, thus resulting in `Int()`.
  
  The coercion works by looking for a method with the same name as the target type: if such method is found on the argument, it is invoked to convert the latter to the expected narrow type. From the above, it is clear that it is possible to provide coercion among user types just providing the required methods:
  
  ```raku
  class Bar {
     has $.msg;
  }
  
  class Foo {
     has $.msg = "I'm a foo!";
  
     # allows coercion from Foo to Bar
     method Bar {
         Bar.new(:msg($.msg ~ ' But I am now Bar.'));
     }
  }
  
  # wants a Bar, but accepts Any
  sub print-bar(Bar() $bar) {
     say $bar.^name; # OUTPUT: «Bar␤»
     say $bar.msg;   # OUTPUT: «I'm a foo! But I am now Bar.␤»
  }
  
  print-bar Foo.new;
  
  ```
  
  In the above code, once a `Foo` instance is passed as argument to `print-bar`, the `Foo.Bar` method is called and the result is placed into `$bar`.
  
  Coercion types are supposed to work wherever types work, but Rakudo currently (2018.05) only implements them in signatures, for both parameters and return types.
  
  Coercion also works with return types:
  
  ```raku
  sub are-equal (Int $x, Int $y --> Bool(Int) ) { $x - $y };
  
  for (2,4) X (1,2) -> ($a,$b) {
      say "Are $a and $b equal? ", are-equal($a, $b);
  } #  OUTPUT: «Are 2 and 1 equal? True␤Are 2 and 2 equal? False␤Are 4 and 1 equal? True␤Are 4 and 2 equal? True␤»
  
  ```
  
  In this case, we are coercing an [`Int`](/type/Int) to a [`Bool`](/type/Bool), which is then printed (put into a string context) in the `for` loop that calls the function.
  
  # [sub MAIN](#Functions "go to top of document")[§](#sub_MAIN "direct link")
  
  Declaring a `sub MAIN` is not compulsory in Raku scripts, but you can provide one to create a [command line interface](/language/create-cli) for your script.
  