txt: ## routine.md
  class Routine
  
  Code object with its own lexical scope and `return` handling
  
  ```raku
  class Routine is Block { }
  ```
  
  A `Routine` is a code object meant for units of code larger than [`Block`](/type/Block). Routine is the common superclass for [`Sub`](/type/Sub) (and therefore operators) and [`Method`](/type/Method), the two primary code objects for code reuse, as well as [`Macro`](/type/Macro) and [`Submethod`](/type/Submethod).
  
  Routines serve as a scope limiter for `return` (i.e. a `return` returns from the innermost outer Routine).
  
  The routine level is also the one at which [multiness](/language/glossary#Multi-dispatch) (multi subs and multi methods) are handled. Subroutines can also be declared `anon`. See the [documentation on the `anon` declarator](/language/variables#The_anon_declarator) for more information.
  
  Routines are the lowest objects in the [`Code`](/type/Code) hierarchy that can introspect through the [`&?ROUTINE` variable](/language/variables#%26%3FROUTINE), which is defined automatically, and contains the corresponding `Routine` object.
  
  ```raku
  class Foo {
      submethod bar { &?ROUTINE.^name }
  };
  say Foo.bar; # OUTPUT: «Submethod␤»
  
  ```
  
  # [Methods](#class_Routine "go to top of document")[§](#Methods "direct link")
  
  ## [method name](#class_Routine "go to top of document")[§](#method_name "direct link")
  
  ```raku
  method name(Routine:D: --> Str:D)
  ```
  
  Returns the name of the sub or method.
  
  ## [method package](#class_Routine "go to top of document")[§](#method_package "direct link")
  
  ```raku
  method package(Routine:D:)
  ```
  
  Returns the package in which the routine is defined.
  
  ## [method multi](#class_Routine "go to top of document")[§](#method_multi "direct link")
  
  ```raku
  method multi(Routine:D: --> Bool:D)
  ```
  
  Returns `True` if the routine is a multi sub or method. Note that the name of a multi sub refers to its [`proto`](/syntax/proto) and this method would return false if called on it. It needs to be called on the candidates themselves:
  
  ```raku
  multi foo ($, $) {};
  say &foo.multi;             # OUTPUT: «False␤»
  say &foo.candidates».multi; # OUTPUT: «(True)␤»
  ```
  
  ## [method candidates](#class_Routine "go to top of document")[§](#method_candidates "direct link")
  
  ```raku
  method candidates(Routine:D: --> Positional:D)
  ```
  
  Returns a list of multi candidates, or a one-element list with itself if it's not a multi
  
  ## [method cando](#class_Routine "go to top of document")[§](#method_cando "direct link")
  
  ```raku
  method cando(Capture $c)
  ```
  
  Returns a possibly-empty list of candidates that can be called with the given [`Capture`](/type/Capture), ordered by narrowest candidate first. For methods, the first element of the Capture needs to be the invocant:
  
  ```raku
  .signature.say for "foo".^can("comb")[0].cando: \(Cool, "o");
  # OUTPUT: «(Cool $: Str $matcher, $limit = Inf, *%_)␤»
  ```
  
  ## [method wrap](#class_Routine "go to top of document")[§](#method_wrap "direct link")
  
  ```raku
  method wrap(Routine:D: &wrapper)
  ```
  
  Wraps (i.e. in-place modifies) the routine. That means a call to this routine first calls `&wrapper`, which then can (but doesn't have to) call the original routine with the `callsame`, `callwith`, `nextsame` and `nextwith` dispatchers. The return value from the routine is also the return value from the wrapper.
  
  `wrap` returns an instance of a private class called [`Routine::WrapHandle`](/type/Routine/WrapHandle), which you can pass to [unwrap](/routine/unwrap) to restore the original routine.
  
  ## [method unwrap](#class_Routine "go to top of document")[§](#method_unwrap "direct link")
  
  ```raku
  method unwrap($wraphandle)
  ```
  
  Restores the original routine after it has been wrapped with [wrap](/routine/wrap). While the signature allows any type to be passed, only the [`Routine::WrapHandle`](/type/Routine/WrapHandle) type returned from `wrap` can usefully be.
  
  ## [method is-wrapped](#class_Routine "go to top of document")[§](#method_is-wrapped "direct link")
  
  ```raku
  method is-wrapped()
  ```
  
  Returns `True` or `False`, depending on the whether or not the `Routine` is wrapped.
  
  ## [method yada](#class_Routine "go to top of document")[§](#method_yada "direct link")
  
  ```raku
  method yada(Routine:D: --> Bool:D)
  ```
  
  Returns `True` if the routine is a stub
  
  ```raku
  say (sub f() { ... }).yada;      # OUTPUT: «True␤»
  say (sub g() { 1;  }).yada;      # OUTPUT: «False␤»
  ```
  
  ## [trait is cached](#class_Routine "go to top of document")[§](#trait_is_cached "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine $r, :$cached!)
  ```
  
  Causes the return value of a routine to be stored, so that when subsequent calls with the same list of arguments are made, the stored value can be returned immediately instead of re-running the routine.[[1]](#fn1)
  
  Useful when storing and returning the computed value is much faster than re-computing it every time, and when the time saved trumps the cost of the use of more memory.
  
  Even if the arguments passed to the routine are "reference types" (such as objects or arrays), then for the purpose of caching they will only be compared based on their contents. Thus the second invocation will hit the cache in this case:
  
  ```raku
  say foo( [1, 2, 3] );   # runs foo
  say foo( [1, 2, 3] );   # doesn't run foo, uses cached value
  
  ```
  
  Since it's still at the experimental stage, you will have to insert the `use experimental :cached;` statement in any module or script that uses it.
  
  ```raku
  use experimental :cached;
  
  sub nth-prime(Int:D $x where * > 0) is cached {
      say "Calculating {$x}th prime";
      return (2..*).grep(*.is-prime)[$x - 1];
  }
  
  say nth-prime(43);
  say nth-prime(43);
  say nth-prime(43);
  
  ```
  
  produces this output:
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  Calculating 43th prime
  191
  191
  191
  
  
  ```
  
  
  ```
  
  **Note**: This feature is not thread-safe.
  
  ## [trait is pure](#class_Routine "go to top of document")[§](#trait_is_pure "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine $r, :$pure!)
  ```
  
  Marks a subroutine as *pure*, that is, it asserts that for the same input, it will always produce the same output without any additional side effects.
  
  The `is pure` trait is a promise by the programmer to the compiler that it can constant-fold calls to such functions when the arguments are known at compile time.
  
  ```raku
  sub syllables() is pure {
      say "Generating syllables";
      my @vowels = <a e i o u>;
      return  @vowels.append: <k m n sh d r t y> X~ @vowels;
  }
  ```
  
  You can mark function as pure even if they throw exceptions in edge cases or if they modify temporary objects; hence the `is pure` trait can cover cases that the compiler cannot deduce on its own. On the other hand, you might not want to constant-fold functions that produce a large return value (such as the string or list repetition operators, infix `x` and `xx`) even if they are pure, to avoid large precompilation files.
  
  To see it an action with a particular compiler you can try this example:
  
  ```raku
  BEGIN { say ‘Begin’ }
  say ‘Start’;
  say (^100).map: { syllables().pick(4).join("") };
  
  
  # Example output:
  # Begin
  # Generating syllables
  # Start
  # (matiroi yeterani shoriyuru...
  
  ```
  
  Essentially this allows the compiler to perform some operations at compile time. The benefits of constant-folding *may* include better performance, especially in cases when the folded code is precompiled.
  
  In addition, using a pure function or operator in sink context (that is, where the result is discarded) may lead to a warning. The code
  
  ```raku
  sub double($x) is pure { 2 * $x };
  double(21);
  say "anything";
  # WARNING: «Useless use of "double(21)" in expression "double(21)" in sink context (line 2)»
  ```
  
  If you want to apply this trait to a `multi`, you need to apply it to the `proto`; it will not work otherwise, at least in versions 2018.08 and below.
  
  ## [trait is rw](#class_Routine "go to top of document")[§](#trait_is_rw "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine $r, :$rw!)
  ```
  
  When a routine is modified with this trait, its return value will be writable. This is useful when returning variables or writable elements of hashes or arrays, for example:
  
  ```raku
  sub walk(\thing, *@keys) is rw {
      my $current := thing;
      for @keys -> $k {
          if $k ~~ Int {
              $current := $current[$k];
          }
          else {
              $current := $current{$k};
          }
      }
      $current;
  }
  
  my %hash;
  walk(%hash, 'some', 'key', 1, 2) = 'autovivified';
  
  say %hash.raku;
  
  ```
  
  produces
  
  ```raku
  ("some" => {"key" => [Any, [Any, Any, "autovivified"]]}).hash
  
  ```
  
  Note that `return` marks return values as read only; if you need an early exit from an `is rw` routine, you have to use `return-rw` instead.
  
  ## [trait is export](#class_Routine "go to top of document")[§](#trait_is_export "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine $r, :$export!)
  ```
  
  Marks a routine as exported to the rest of the world
  
  ```raku
  module Foo {
      sub double($x) is export {
          2 * $x
      }
  }
  
  import Foo;         # makes sub double available
  say double 21;      # 42
  
  ```
  
  From inside another file you'd say `use Foo;` to load a module and import the exported functions.
  
  See [Exporting and Selective Importing Modules](/language/modules#Exporting_and_selective_importing) for more details.
  
  ## [trait is DEPRECATED](#class_Routine "go to top of document")[§](#trait_is_DEPRECATED "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine:D $r, :$DEPRECATED!)
  ```
  
  Marks a `Routine` as deprecated; that is, it should no longer be used going forward, and will eventually be removed. An optional message specifying the replacement functionality can be specified
  
  By having both the original (deprecated) and new `Routine` available simultaneously, you can avoid a breaking change in a single release, by allowing users time and instructions on how to update their code. Remove the deprecated version only after at least one release that includes both the warning and the new `Routine`.
  
  This code
  
  ```raku
  sub f() is DEPRECATED('the literal 42') { 42 }
  say f();
  
  ```
  
  produces this output:
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  42
  Saw 1 occurrence of deprecated code.
  ================================================================================
  Sub f (from GLOBAL) seen at:
    deprecated.raku, line 2
  Please use the literal 42 instead.
  --------------------------------------------------------------------------------
  Please contact the author to have these occurrences of deprecated code
  adapted, so that this message will disappear!
  
  
  ```
  
  
  ```
  
  ## [trait is hidden-from-backtrace](#class_Routine "go to top of document")[§](#trait_is_hidden-from-backtrace "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine:D, :$hidden-from-backtrace!)
  ```
  
  Hides a routine from showing up in a default backtrace. For example
  
  ```raku
  sub inner { die "OH NOEZ" };
  sub outer { inner() };
  outer();
  
  ```
  
  produces the error message and backtrace
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  OH NOEZ
    in sub inner at bt.raku:1
    in sub outer at bt.raku:2
    in block <unit> at bt.raku:3
  
  
  ```
  
  
  ```
  
  but if `inner` is marked with `hidden-from-backtrace`
  
  ```raku
  sub inner is hidden-from-backtrace { die "OH NOEZ" };
  sub outer { inner() };
  outer();
  
  ```
  
  the error backtrace does not show it:
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  OH NOEZ
    in sub outer at bt.raku:2
    in block <unit> at bt.raku:3
  
  
  ```
  
  
  ```
  
  ## [trait is default](#class_Routine "go to top of document")[§](#trait_is_default "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine:D $r, :$default!)
  ```
  
  There is a special trait for `Routine`s called `is default`. This trait is designed as a way to disambiguate `multi` calls that would normally throw an error because the compiler would not know which one to use. This means that given the following two `Routine`s, the one with the `is default` trait will be called.
  
  ```raku
  multi f() is default { say "Hello there" }
  multi f() { say "Hello friend" }
  f();   # OUTPUT: «"Hello there"␤»
  ```
  
  The `is default` trait can become very useful for debugging and other uses but keep in mind that it will only resolve an ambiguous dispatch between two `Routine`s of the same precedence. If one of the `Routine`s is narrower than another, then that one will be called. For example:
  
  ```raku
  multi f() is default { say "Hello there" }
  multi f(:$greet) { say "Hello " ~ $greet }
  f();   # "Use of uninitialized value $greet..."
  
  ```
  
  In this example, the `multi` without `is default` was called because it was actually narrower than the [`Sub`](/type/Sub) with it.
  
  ## [trait is raw](#class_Routine "go to top of document")[§](#trait_is_raw "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine:D $r, :$raw!)
  ```
  
  Gives total access to the data structure returned by the routine.
  
  ```raku
  my @zipi = <zape zapatilla>;
  sub þor() is raw {
      return @zipi
  };
  þor()[1] = 'pantuflo';
  say @zipi;  # OUTPUT: «[zape pantuflo]␤»
  
  ```
  
  ## [trait is test-assertion](#class_Routine "go to top of document")[§](#trait_is_test-assertion "direct link")
  
  ```raku
  multi trait_mod:<is>(Routine:D, :$test-assertion!)
  ```
  
  Declares that a routine generates test output (aka TAP). When failures are reported, the calling routine's location is used instead of this routine. For example:
  
  ```raku
  use Test;
  sub foo-test($value) is test-assertion {
      is $value, 42, "is the value 42?";
  }
  foo-test(666);    # <-- error is reported on this line
  
  ```
  
  # [Typegraph](# "go to top of document")[§](#typegraphrelations "direct link")
  
  Type relations for `Routine`
  
  
  
  raku-type-graph
  
  
  
  Routine
  Routine
  
  
  Block
  Block
  
  
  Routine->Block
  
  
  
  Mu
  Mu
  
  
  Any
  Any
  
  
  Any->Mu
  
  
  
  Callable
  Callable
  
  
  Code
  Code
  
  
  Code->Any
  
  
  
  Code->Callable
  
  
  
  Block->Code
  
  
  
  Sub
  Sub
  
  
  Sub->Routine
  
  
  
  Method
  Method
  
  
  Method->Routine
  
  
  
  Macro
  Macro
  
  
  Macro->Routine
  
  
  
  Submethod
  Submethod
  
  
  Submethod->Routine
  
  
  
  Regex
  Regex
  
  
  Regex->Method
  
  [Expand chart above](/assets/typegraphs/Routine.svg)
  
  1 [[↑]](#fnret1) This is still in experimental stage. Please check [the corresponding section in the experimental features document](/language/experimental#cached)
  