txt: ## functions.md
  ## Chunk 1 of 2
  Functions
  
  Functions and functional programming in Raku
  
  Routines are one of the means Raku has to reuse code. They come in several forms, most notably [`Method`](/type/Method)s, which belong in classes and roles and are associated with an object; and functions (also called *subroutines* or [`Sub`](/type/Sub)s, for short), which can be called independently of objects.
  
  Subroutines default to lexical (`my`) scoping, and calls to them are generally resolved at compile time.
  
  Subroutines can have a [`Signature`](/type/Signature), also called *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 the return value.
  
  Introspection on subroutines is provided via [`Routine`](/type/Routine).
  
  # [Defining/Creating/Using functions](#Functions "go to top of document")[§](#Defining/Creating/Using_functions "direct link")
  
  ## [Subroutines](#Functions "go to top of document")[§](#Subroutines "direct link")
  
  The basic way to create a subroutine is to use the `sub` declarator followed by an optional [identifier](/language/syntax#Identifiers):
  
  ```raku
  sub my-func { say "Look ma, no args!" }
  my-func;
  ```
  
  The sub declarator returns a value of type [`Sub`](/type/Sub) that can be stored in any container:
  
  ```raku
  my &c = sub { say "Look ma, no name!" }
  c;     # OUTPUT: «Look ma, no name!␤»
  
  my Any:D $f = sub { say 'Still nameless...' }
  $f();  # OUTPUT: «Still nameless...␤»
  
  my Code \a = sub { say ‚raw containers don't implement postcircumfix:<( )>‘ };
  a.();  # OUTPUT: «raw containers don't implement postcircumfix:<( )>␤»
  ```
  
  The declarator `sub` will declare a new name in the current scope at compile time. As such, any indirection has to be resolved at compile time:
  
  ```raku
  constant aname = 'foo';
  sub ::(aname) { say 'oi‽' };
  foo;
  ```
  
  This will become more useful once macros are added to Raku.
  
  To have the subroutine take arguments, a [`Signature`](/type/Signature) goes between the subroutine's name and its body, in parentheses:
  
  ```raku
  sub exclaim ($phrase) {
      say $phrase ~ "!!!!"
  }
  exclaim "Howdy, World";
  
  ```
  
  By default, subroutines are [lexically scoped](/syntax/my). That is, `sub foo {...}` is the same as `my sub foo {...}` and is only defined within the current scope.
  
  ```raku
  sub escape($str) {
      # Puts a slash before non-alphanumeric characters
      S:g[<-alpha -digit>] = "\\$/" given $str
  }
  
  say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
  
  {
      sub escape($str) {
          # Writes each non-alphanumeric character in its hexadecimal escape
          S:g[<-alpha -digit>] = "\\x[{ $/.ord.base(16) }]" given $str
      }
  
      say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤»
  }
  
  # Back to original escape function
  say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
  
  ```
  
  Subroutines don't have to be named. If unnamed, they're called *anonymous* subroutines.
  
  ```raku
  say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # OUTPUT: «25␤»
  ```
  
  But in this case, it's often desirable to use the more succinct [`Block`](/type/Block) syntax. Subroutines and blocks can be called in place, as in the example above.
  
  ```raku
  say -> $a, $b { $a ** 2 + $b ** 2 }(3, 4)    # OUTPUT: «25␤»
  ```
  
  Or even
  
  ```raku
  say { $^a ** 2 + $^b ** 2 }(3, 4)            # OUTPUT: «25␤»
  ```
  
  ## [Blocks and lambdas](#Functions "go to top of document")[§](#Blocks_and_lambdas "direct link")
  
  Whenever you see something like `{ $_ + 42 }`, `-> $a, $b { $a ** $b }`, or `{ $^text.indent($:spaces) }`, that's [`Block`](/type/Block) syntax; the `->` is considered also part of the block. Statements such as `if`, `for`, `while` are followed by these kind of blocks.
  
  ```raku
  for 1, 2, 3, 4 -> $a, $b {
      say $a ~ $b;
  }
  # OUTPUT: «12␤34␤»
  ```
  
  They can also be used on their own as anonymous blocks of code.
  
  ```raku
  say { $^a ** 2 + $^b ** 2}(3, 4) # OUTPUT: «25␤»
  ```
  
  Please note that this implies that, despite the fact that statements such as `if` do not define a topic variable, they actually can:
  
  ```raku
  my $foo = 33;
  if $foo ** 33 -> $a {
      say "$a is not null"; #
  } # OUTPUT: «129110040087761027839616029934664535539337183380513 is not null␤»
  
  ```
  
  For block syntax details, see the documentation for the [`Block`](/type/Block) type.
  
  ## [Signatures](#Functions "go to top of document")[§](#Signatures "direct link")
  
  The parameters that a function accepts are described in its *signature*.
  
  ```raku
  sub format(Str $s) { ... }
  -> $a, $b { ... }
  
  ```
  
  Details about the syntax and use of signatures can be found in the [documentation on the `Signature` class](/type/Signature).
  
  ### [Automatic signatures](#Functions "go to top of document")[§](#Automatic_signatures "direct link")
  
  If no signature is provided but either of the two automatic variables `@_` or `%_` are used in the function body, a signature with `*@_` or `*%_` will be generated. Both automatic variables can be used at the same time.
  
  ```raku
  sub s { say @_, %_ };
  say &s.signature # OUTPUT: «(*@_, *%_)␤»
  ```
  
  ## [Arguments](#Functions "go to top of document")[§](#Arguments "direct link")
  
  Arguments are supplied as a comma separated list. To disambiguate nested calls, use parentheses:
  
  ```raku
  sub f(&c){ c() * 2 }; # call the function reference c with empty parameter list
  sub g($p){ $p - 2 };
  say(g(42), 45);       # pass only 42 to g()
  ```
  
  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's considered good form to place named arguments after positional arguments. Inside the argument list of a function call, some special syntax is supported:
  
  ```raku
  sub f(|c){};
  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 'hi', :1x, :2y; # Positional and named arguments
  my \c = <a b c>.Capture;
  f |c;             # Merge the contents of Capture $c as if they were supplied
  ```
  
  Arguments passed to a function are conceptually first collected in a [`Capture`](/type/Capture) container. Details about the syntax and use of these containers can be found in [`Capture`](/type/Capture)'s documentation.
  
  When using named arguments, note that normal list "pair-chaining" allows one to skip commas between named arguments.
  
  ```raku
  sub f(|c){};
  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.
  ```
  
  If positional arguments are also passed, then either they must be passed within parentheses placed *immediately* after the function's name or the comma after the last positional argument must be kept when chaining named arguments in abbreviated adverb form. The spaces between chained named arguments and the list of positional arguments is optional.
  
  ```raku
  sub p($x, $y, :$translate, :$rotate) {};
  p(1, 1, :translate, :rotate); # normal way
  p 1, 1, :translate, :rotate;  # also normal way
  
  p(1, 1) :translate  :rotate;  # parentheses + chained named arguments
  p(1, 1) :translate:rotate;
  p(1, 1):translate:rotate;
  
  p 1, 1, :translate  :rotate;  # dangling comma + chained named arguments
  p 1, 1, :translate:rotate;
  p 1, 1,:translate:rotate;
  ```
  
  ## [Return values](#Functions "go to top of document")[§](#Return_values "direct link")
  
  Any [`Block`](/type/Block) or [`Routine`](/type/Routine) will provide the value of its last expression as a return value to the caller. If either [return](/language/control#return) or [return-rw](/language/control#return-rw) is called, then its parameter, if any, will become the return value. The default return value is [`Nil`](/type/Nil).
  
  ```raku
  sub a { 42 };
  sub b { say a };
  sub c { };
  b;     # OUTPUT: «42␤»
  say c; # OUTPUT: «Nil␤»
  ```
  
  Multiple return values are returned as a list or by creating a [`Capture`](/type/Capture). Destructuring can be used to untangle multiple return values.
  
  ```raku
  sub a { 42, 'answer' };
  put a.raku;
  # OUTPUT: «(42, "answer")␤»
  
  my ($n, $s) = a;
  put [$s, $n];
  # OUTPUT: «answer 42␤»
  
  sub b { <a b c>.Capture };
  put b.raku;
  # OUTPUT: «\("a", "b", "c")␤»
  ```
  
  ## [Return type constraints](#Functions "go to top of document")[§](#Return_type_constraints "direct link")
  
  Raku has many ways to specify a function's return type:
  
  ```raku
  sub foo(--> Int)      {}; say &foo.returns; # OUTPUT: «(Int)␤»
  
  ```
  
  ```raku
  sub foo() returns Int {}; say &foo.returns; # OUTPUT: «(Int)␤»
  
  ```
  
  ```raku
  sub foo() of Int      {}; say &foo.returns; # OUTPUT: «(Int)␤»
  
  ```
  
  ```raku
  my Int sub foo()      {}; say &foo.returns; # OUTPUT: «(Int)␤»
  
  ```
  
  Attempting to return values of another type will cause a compilation error.
  
  ```raku
  sub foo() returns Int { "a"; }; foo; # Type check fails
  
  ```
  
  `returns` and `of` are equivalent, and both take only a Type since they are declaring a trait of the [`Callable`](/type/Callable). The last declaration is, in fact, a type declaration, which obviously can take only a type. In the other hand, `-->` can take either undefined or definite values.
  
  Note that [`Nil`](/type/Nil) and [`Failure`](/type/Failure) are exempt from return type constraints and can be returned from any routine, regardless of its constraint:
  
  ```raku
  sub foo() returns Int { fail   }; foo; # Failure returned
  sub bar() returns Int { return }; bar; # Nil returned
  
  ```
  
  ## [Multi-dispatch](#Functions "go to top of document")[§](#Multi-dispatch "direct link")
  
  Raku allows for writing several routines with the same name but different signatures. When the routine is called by name, the runtime environment determines the proper *candidate* and invokes it.
  
  Each candidate is declared with the `multi` keyword. Dispatch happens depending on the parameter [arity](/type/Code#method_arity) (number), type and name; and under some circumstances the order of the multi declarations. Consider the following example:
  
  ```raku
  # version 1
  multi happy-birthday( $name ) {
      say "Happy Birthday $name !";
  }
  
  # version 2
  multi happy-birthday( $name, $age ) {
      say "Happy {$age}th Birthday $name !";
  }
  
  # version 3
  multi happy-birthday( :$name, :$age, :$title  = 'Mr' ) {
      say "Happy {$age}th Birthday $title $name !";
  }
  
  
  # calls version 1 (arity)
  happy-birthday 'Larry';                        # OUTPUT: «Happy Birthday Larry !␤»
  # calls version 2 (arity)
  happy-birthday 'Luca', 40;                     # OUTPUT: «Happy 40th Birthday Luca !␤»
  # calls version 3
  # (named arguments win against arity)
  happy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤»
  # calls version 2 (arity)
  happy-birthday( 'Jack', 25 );                  # OUTPUT: «Happy 25th Birthday Jack !␤»
  
  ```
  
  The first two versions of the `happy-birthday` sub differs only in the arity (number of arguments), while the third version uses named arguments and is chosen only when named arguments are used, even if the arity is the same of another `multi` candidate.
  
  When two sub have the same arity, the type of the arguments drive the dispatch; when there are named arguments they drive the dispatch even when their type is the same as another candidate:
  
  ```raku
  multi happy-birthday( Str $name, Int $age ) {
      say "Happy {$age}th Birthday $name !";
  }
  
  multi happy-birthday( Str $name, Str $title ) {
      say "Happy Birthday $title $name !";
  }
  
  multi happy-birthday( Str :$name, Int :$age ) {
      say "Happy Birthday $name, you turned $age !";
  }
  
  happy-birthday 'Luca', 40;                 # OUTPUT: «Happy 40th Birthday Luca !␤»
  happy-birthday 'Luca', 'Mr';               # OUTPUT: «Happy Birthday Mr Luca !␤»
  happy-birthday age => 40, name => 'Luca';  # OUTPUT: «Happy Birthday Luca, you turned 40 !␤»
  
  ```
  
  Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence.
  
  For more information about type constraints see the documentation on [`Signature` literals](/language/signatures#Type_constraints).
  
  ```raku
  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 );                        # OUTPUT: «true␤»
  say as-json( 10.3 );                        # OUTPUT: «10.3␤»
  say as-json( [ True, 10.3, False, 24 ] );   # OUTPUT: «[true, 10.3, false, 24]␤»
  ```
  
  For some signature differences (notably when using a where clause or a subset) the order of definition of the multi methods or subs is used, evaluating each possibility in turn. See [multi resolution by order of definition](/language/functions#multi_resolution_by_order_of_definition) below for examples.
  
  `multi` without any specific routine type always defaults to a `sub`, but you can use it on methods as well. The candidates are all the multi methods of the object:
  
  ```raku
  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'); # OUTPUT: «Hooray for your promotion, Cindy␤»
  $congrats.congratulate('birthday','Bob');    # OUTPUT: «Happy birthday, Bob␤»
  ```
  
  Unlike `sub`, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected.
  
  Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates.
  
  Multi-dispatch can also work on parameter traits, with routines with `is rw` parameters having a higher priority than those that do not:
  
  ```raku
  proto þoo (|) {*}
  multi þoo( $ðar is rw ) { $ðar = 42 }
  multi þoo( $ðar ) { $ðar + 42 }
  my $bar = 7;
  say þoo($bar); # OUTPUT: «42␤»
  
  ```
  
  ### [proto](#Functions "go to top of document")[§](#proto "direct link")
  
  `proto` is a way to formally declare commonalities between `multi` candidates. It acts as a wrapper that can validate but not modify arguments. Consider this basic example:
  
  ```raku
  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 -- got rank $rank!";
  }
  
  congratulate('being a cool number', 'Fred');     # OK
  congratulate('being a cool number', 'Fred', 42); # OK
  ```
  
  ```raku
  congratulate('being a cool number', 42);         # Proto match error
  
  ```
  
  The proto insists that all `multi congratulate` subs conform to the basic signature of two strings, optionally followed by further parameters. The `|` is an un-named [`Capture`](/type/Capture) parameter, and allows a `multi` to take additional arguments. The first two calls succeed, but the third fails (at compile time) because `42` doesn't match [`Str`](/type/Str).
  
  ```raku
  say &congratulate.signature # OUTPUT: «(Str $reason, Str $name, | is raw)␤»
  
  ```
  
  You can give the `proto` a function body, and place the `{*}` (note there is no whitespace inside the curly braces) where you want the dispatch to be done. This can be useful when you have a "hole" in your routine that gives it different behavior depending on the arguments given:
  
  ```raku
  # attempts to notify someone -- False if unsuccessful
  proto notify(Str $user, Str $msg) {
     my \hour = DateTime.now.hour;
     if 8 < hour < 22 {
        return {*};
     } else {
        # we can't notify someone when they might be sleeping
        return False;
     }
  }
  ```
  
  Since `proto` is a wrapper for `multi` candidates, the signatures of the routine's `multi` candidates do not necessarily have to match that of the `proto`; arguments of `multi` candidates may have subtypes of those of the `proto`, and the return types of the `multi` candidates may be entirely different from that of the `proto`. Using differing types like this is especially useful when giving `proto` a function body:
  
  ```raku
  enum DebugType <LOG WARNING ERROR>;
  
  #|[ Prints a message to stderr with a color-coded key. ]
  proto debug(DebugType:D $type, Str:D $message --> Bool:_) {
      note sprintf qb/\e[1;%dm[%s]\e[0m %s/, {*}, $type.key, $message
  }
  multi debug(LOG;; Str:D --> 32)     { }
  multi debug(WARNING;; Str:D --> 33) { }
  multi debug(ERROR;; Str:D --> 31)   { }
  
  ```
  
  `{*}` always dispatches to candidates with the parameters it's called with. Parameter defaults and type coercions will work but are not passed on.
  
  ```raku
  proto mistake-proto(Str() $str, Int $number = 42) {*}
  multi mistake-proto($str, $number) { say $str.^name }
  mistake-proto(7, 42);  # OUTPUT: «Int␤» -- not passed on
  
  ```
  
  ```raku
  mistake-proto('test'); # fails -- not passed on
  
  ```
  
  A longer example using `proto` for methods shows how to extract common functionality into a proto method.
  
  ```raku
  class NewClass {
      has $.debug is rw = False;
      has $.value is rw = 'Initial value';
      proto method handle( | ) {
          note "before value is ｢$.value｣" if $.debug;
          {*}
          note "after value is ｢$.value｣" if $.debug;
      }
      multi method handle(Str $s) {
          $.value = $s;
          say 'in string'
      }
      multi method handle(Positional $s) {
          $.value = $s[0];
          say 'in positional'
      }
      multi method handle( $a, $b ) {
          $.value = "$a is looking askance at $b";
          say 'with more than one value'
      }
  }
  my NewClass $x .= new;
  $x.handle('hello world');
  $x.handle(<hello world>);
  $x.debug = True;
  $x.handle('hello world');
  $x.handle(<hello world>);
  $x.handle('Claire', 'John');
  # OUTPUT:
  # in string
  # in positional
  # before value is ｢hello｣
  # in string
  # after value is ｢hello world｣
  # before value is ｢hello world｣
  # in positional
  # after value is ｢hello｣
  # before value is ｢hello｣
  # with more than one value
  # after value is ｢Claire is looking askance at John｣
  
  ```
  
  ### [only](#Functions "go to top of document")[§](#only "direct link")
  
  The `only` keyword preceding `sub` or `method` indicates that it will be the only function with that name that inhabits a given namespace.
  
  ```raku
  only sub you () {"Can make all the world seem right"};
  ```
  
  This will make other declarations in the same namespace, such as
  
  ```raku
  sub you ( $can ) { "Make the darkness bright" }
  ```
  
  fail with an exception of type [`X::Redeclaration`](/type/X/Redeclaration). `only` is the default value for all subs; in the case above, not declaring the first subroutine as `only` will yield exactly the same error; however, nothing prevents future developers from declaring a proto and preceding the names with `multi`. Using `only` before a routine is a [defensive programming](https://en.wikipedia.org/wiki/Defensive_programming) feature that declares the intention of not having routines with the same name declared in the same namespace in the future.
  
  ｢text｣ without highlighting
  
  ```
  
  
  ```
  
  (exit code 1)
  ===SORRY!=== Error while compiling /tmp/only-redeclaration.raku
  Redeclaration of routine 'you' (did you mean to declare a multi-sub?)
  at /tmp/only-redeclaration.raku:3
  ------> <BOL>⏏<EOL>
  
  
  ```
  
  
  ```
  
  Anonymous subs cannot be declared `only`. `only sub {}` will throw an error of type, surprisingly, [`X::Anon::Multi`](/type/X/Anon/Multi).
  
  ### [multi resolution by order of definition](#Functions "go to top of document")[§](#multi_resolution_by_order_of_definition "direct link")
  
  When the breakdown by parameter type is not enough to find an unambiguous match, there are some different tie breakers that may be evaluated in order of declaration of the methods or subs: these include where clauses and subsets, named parameters, and signature unpacks.
  
  In this code example, two multi subs are distinguished only by where clauses where there's one ambiguous case that might pass either of them, the value 4. In this case, which ever multi sub is defined first wins:
  
  ```raku
  {
    multi check_range ( Int $n where {$_ > 3} ) {
        return "over 3";
    };
    multi check_range ( Int $n where {$_ < 5} ) {
        return "under 5";
    };
    say check_range(4);  # OUTPUT: over 3
  }
  {
    multi check_range ( Int $n where {$_ < 5} ) {
        return "under 5";
    };
    multi check_range ( Int $n where {$_ > 3} ) {
        return "over 3";
    };
    say check_range(4);  # OUTPUT: under 5
  }
  
  ```
  
  In the following example, three subsets are used to restrict strings to certain allowed values, where there are overlaps between all three:
  
  ```raku
  subset Monster  of Str where { $_ eq any( <godzilla gammera ghidora> ) };
  subset Hero     of Str where { $_ eq any( <godzilla ultraman inframan> ) };
  subset Knockoff of Str where { $_ eq any( <gammera inframan thorndike> ) };
  
  {
      multi speak (Monster $name) {
          say "The monster, $name roars!";
      }
      multi speak (Hero $name) {
          say "The hero, $name shouts!";
      }
      multi speak (Knockoff $name) {
          say "The knockoff, $name, slinks away...";
      }
      speak('godzilla');     # OUTPUT: The monster, godzilla roars!
      speak('gammera');      # OUTPUT: The monster, gammera roars!
      speak('inframan');     # OUTPUT: The hero, inframan shouts!
  }
  
  ```
  
  Note that here 'godzilla' is treated as Monster, not as Hero, because the Monster multi comes first; and neither 'gammera' or 'inframan' are treated as Knockoff, because that multi comes last.
  
  It should be noted that the order of definition is the order in which Raku sees them, which might not be easy to discern if, for example, the multi subs were imported from different modules. As the organization of a code base becomes more complex, object classes may scale better than using subsets as types, as in this example.
  
  # [Conventions and idioms](#Functions "go to top of document")[§](#Conventions_and_idioms "direct link")
  
  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.
  
  ## [Slurpy conventions](#Functions "go to top of document")[§](#Slurpy_conventions "direct link")
  
  Perhaps the most important one of these conventions 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 (e.g., [chrs](/routine/chrs)) or where there is a conflict with an established idiom (e.g., [pop](/routine/pop) being the inverse of [push](/routine/push)).
  
  If you wish to match this look and feel, any [`Iterable`](/type/Iterable) argument must be broken out element-by-element using a `**@` slurpy, with two nuances:
  
  * An [`Iterable`](/type/Iterable) inside a [Scalar container](/language/containers#Scalar_containers) doesn't count.
  * [`List`](/type/List)s created with a [`,`](/routine/,) at the top level only count as one [`Iterable`](/type/Iterable).
  
  This can be achieved by using a slurpy with a [`+`](/language/signatures#Parameter_traits_and_modifiers) or `+@` instead of `**@`:
  
  ```raku
  sub grab(+@a) { "grab $_".say for @a }
  ```
  
  which is shorthand for something very close to:
  
  ```raku
  multi grab(**@a) { "grab $_".say for @a }
  multi 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:
  
  ```raku
  grab(1, 2);      # OUTPUT: «grab 1␤grab 2␤»
  grab((1, 2));    # OUTPUT: «grab 1␤grab 2␤»
  grab($(1, 2));   # OUTPUT: «grab 1 2␤»
  grab((1, 2), 3); # OUTPUT: «grab 1 2␤grab 3␤»
  
  ```
  
  This also makes user-requested flattening feel consistent whether there is one sublist, or many:
  
  ```raku
  grab(flat (1, 2), (3, 4));   # OUTPUT: «grab 1␤grab 2␤grab 3␤grab 4␤»
  grab(flat $(1, 2), $(3, 4)); # OUTPUT: «grab 1 2␤grab 3 4␤»
  grab(flat (1, 2));           # OUTPUT: «grab 1␤grab 2␤»
  grab(flat $(1, 2));          # OUTPUT: «grab 1␤grab 2␤»
  
  ```
  
  It's worth noting that mixing binding and sigilless variables in these cases requires a bit of finesse, because there is no [`Scalar`](/type/Scalar) intermediary used during binding.
  
  ```raku
  my $a = (1, 2);  # Normal assignment, equivalent to $(1, 2)
  grab($a);        # OUTPUT: «grab 1 2␤»
  my $b := (1, 2); # Binding, $b links directly to a bare (1, 2)
  grab($b);        # OUTPUT: «grab 1␤grab 2␤»
  my \c = (1, 2);  # Sigilless variables always bind, even with '='
  grab(c);         # OUTPUT: «grab 1␤grab 2␤»
  
  ```
  
  See the [documentation of the `list` subroutine](/type/List#routine_list) for more examples of how to use a routine that adheres to the single argument rule.
  
  # [Functions are first-class objects](#Functions "go to top of document")[§](#Functions_are_first-class_objects "direct link")
  
  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:
  
  ```raku
  my $square = sub (Numeric $x) { $x * $x }
  # and then use it:
  say $square(6);    # OUTPUT: «36␤»
  ```
  
  Or you can reference an existing named function by using the `&`-sigil in front of it.
  
  ```raku
  sub square($x) { $x * $x };
  
  # get hold of a reference to the function:
  my $func = &square
  ```
  
  This is very useful for *higher order functions*, that is, functions that take other functions as input. A simple one is [map](/type/List#routine_map), which applies a function to each input element:
  
  ```raku
  sub square($x) { $x * $x };
  my @squared = map &square,  1..5;
  say join ', ', @squared;        # OUTPUT: «1, 4, 9, 16, 25␤»
  ```
  
  You can use the same for operators, except that in that case the name with which they have been declared, using `infix:`, must be used:
  
  ```raku
  my $exp := &infix:<**>; say $exp(7,3); # OUTPUT: «343␤»
  ```
  
  This can be done even in cases where operators have been *auto-generated*, for instance in this case where `XX` is the metaoperator `X` applied to the `X` operator.
  
  ```raku
  my $XX := &infix:<XX>; say $XX( [1,(2,3)] , [(4,5),6]  );
  # OUTPUT: «(((1 (4 5))) ((1 6)) (((2 3) (4 5))) (((2 3) 6)))␤»
  ```
  
  Baseline is that, in case of operators, you don't really need to worry about the actual way they were defined, just use the `&infix< >` to grab a pointer to them.
  
  ## [Infix form](#Functions "go to top of document")[§](#Infix_form "direct link")
  
  To call a subroutine with 2 arguments like an infix operator, use a subroutine reference surrounded by `[` and `]`.
  
  ```raku
  sub plus { $^a + $^b };
  say 21 [&plus] 21;
  # OUTPUT: «42␤»
  ```
  
  ## [Closures](#Functions "go to top of document")[§](#Closures "direct link")
  
  All code objects in Raku are *closures*, which means they can reference lexical variables from an outer scope.
  
  ```raku
  sub generate-sub($x) {
      my $y = 2 * $x;
      return sub { say $y };
      #      ^^^^^^^^^^^^^^  inner sub, uses $y
  }
  my $generated = generate-sub(21);
  $generated(); # OUTPUT: «42␤»
  ```
  
  Here, `$y` is a lexical variable inside `generate-sub`, and the inner subroutine that is returned uses it. By the time that inner sub is called, `generate-sub` has already exited. Yet the inner sub can still use `$y`, because it *closed* over the variable.
  
  Another closure example is the use of [map](/type/List#routine_map) to multiply a list of numbers:
  
  ```raku
  my $multiply-by = 5;
  say join ', ', map { $_ * $multiply-by }, 1..5;     # OUTPUT: «5, 10, 15, 20, 25␤»
  ```
  
  Here, the block passed to `map` references the variable `$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 `map`.
  
  ## [Routines](#Functions "go to top of document")[§](#Routines "direct link")
  
  Routines are code objects that conform to the type [`Routine`](/type/Routine), most notably [`Sub`](/type/Sub), [`Method`](/type/Method), [`Regex`](/type/Regex) and [`Submethod`](/type/Submethod).
  
  They carry extra functionality in addition to what a [`Block`](/type/Block) supplies: they can come as [multis](#Multi-dispatch), you can [wrap](/type/Routine#method_wrap) them, and exit early with `return`:
  
  ```raku
  my $keywords = set <if for unless while>;
  
  sub has-keyword(*@words) {
      for @words -> $word {
          return True if $word (elem) $keywords;
      }
      False;
  }
  
  say has-keyword 'not', 'one', 'here';       # OUTPUT: «False␤»
  say has-keyword 'but', 'here', 'for';       # OUTPUT: «True␤»
  ```
  
  Here, `return` doesn't just leave the block inside which it was called, but the whole routine. In general, blocks are transparent to `return`, they attach to the outermost routine.
  
  Routines can be inlined and as such provide an obstacle for wrapping. Use the pragma `use soft;` to prevent inlining to allow wrapping at runtime.
  
  ```