## dist_zef-antononcube-Text-Calendar.md
# Text::Calendar

Raku package with text calendar functions for displaying monthly, yearly, and custom calendars.

### Motivation

* For data science applications I need sparse calendars that contain only some of the dates
* I want to facilitate making and displaying calendars in Jupyter notebooks using Markdown and HTML layouts
* I like the "transposed" calendar layout of UNIX' `ncal`
* I am interested in comparisons of calendar making (i) with LLM applications, and (ii) in the "hard way"

### Alternative implementations

* ["App::Cal"](https://raku.land/zef:coke/App::Cal), [WCp1].
* ["Calendar"](https://raku.land/zef:tbrowder/Calendar), [TBp1].

Compared to [WCp1] and [TBp1], this package, "Text::Calendar", is lightweight and with no dependencies.

### Extensions

The package ["Markup::Calendar"](https://raku.land/zef:antononcube/Markup::Calendar), [AAp2],
provides calendars in HTML and Markdown formats.

---

## Installation

From [Zef ecosystem](https://raku.land):

```
zef install Text::Calendar

```

From GitHub:

```
zef install https://github.com/antononcube/Raku-Text-Calendar.git

```

---

## Examples

### Emacs style: this month with ones before and after

Load the package and show today's date:

```
use Text::Calendar;
Date.today;

```

```
# 2024-02-09

```

Default, "Emacs style" calendar:

```
calendar();

```

```
# January                February               March
# Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su
#  1  2  3  4  5  6  7             1  2  3  4                1  2  3
#  8  9 10 11 12 13 14    5  6  7  8  9 10 11    4  5  6  7  8  9 10
# 15 16 17 18 19 20 21   12 13 14 15 16 17 18   11 12 13 14 15 16 17
# 22 23 24 25 26 27 28   19 20 21 22 23 24 25   18 19 20 21 22 23 24
# 29 30 31               26 27 28 29            25 26 27 28 29 30 31

```

Compare the output above with the that of UNIX (macOS) function `cal`:

```
cal -3 -h

```

```
# 2024
#       January               February               March
# Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
#     1  2  3  4  5  6               1  2  3                  1  2
#  7  8  9 10 11 12 13   4  5  6  7  8  9 10   3  4  5  6  7  8  9
# 14 15 16 17 18 19 20  11 12 13 14 15 16 17  10 11 12 13 14 15 16
# 21 22 23 24 25 26 27  18 19 20 21 22 23 24  17 18 19 20 21 22 23
# 28 29 30 31           25 26 27 28 29        24 25 26 27 28 29 30
#                                             31

```

Here is the "transposed" version (or UNIX `ncal` style):

```
say "ncal style:\n", calendar(:transposed);

```

```
# ncal style:
#     January 2024    February 2024   March 2024
# Mo  1  8 15 22 29      5 12 19 26      4 11 18 25
# Tu  2  9 16 23 30      6 13 20 27      5 12 19 26
# We  3 10 17 24 31      7 14 21 28      6 13 20 27
# Th  4 11 18 25      1  8 15 22 29      7 14 21 28
# Fr  5 12 19 26      2  9 16 23      1  8 15 22 29
# Sa  6 13 20 27      3 10 17 24      2  9 16 23 30
# Su  7 14 21 28      4 11 18 25      3 10 17 24 31

```

### Yearly

```
calendar-year(2024, per-row=>6)

```

```
# 2024
#
# January                February               March                  April                  May                    June
# Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su
#  1  2  3  4  5  6  7             1  2  3  4                1  2  3    1  2  3  4  5  6  7          1  2  3  4  5                   1  2
#  8  9 10 11 12 13 14    5  6  7  8  9 10 11    4  5  6  7  8  9 10    8  9 10 11 12 13 14    6  7  8  9 10 11 12    3  4  5  6  7  8  9
# 15 16 17 18 19 20 21   12 13 14 15 16 17 18   11 12 13 14 15 16 17   15 16 17 18 19 20 21   13 14 15 16 17 18 19   10 11 12 13 14 15 16
# 22 23 24 25 26 27 28   19 20 21 22 23 24 25   18 19 20 21 22 23 24   22 23 24 25 26 27 28   20 21 22 23 24 25 26   17 18 19 20 21 22 23
# 29 30 31               26 27 28 29            25 26 27 28 29 30 31   29 30                  27 28 29 30 31         24 25 26 27 28 29 30
#
# July                   August                 September              October                November               December
# Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su
#  1  2  3  4  5  6  7             1  2  3  4                      1       1  2  3  4  5  6                1  2  3                      1
#  8  9 10 11 12 13 14    5  6  7  8  9 10 11    2  3  4  5  6  7  8    7  8  9 10 11 12 13    4  5  6  7  8  9 10    2  3  4  5  6  7  8
# 15 16 17 18 19 20 21   12 13 14 15 16 17 18    9 10 11 12 13 14 15   14 15 16 17 18 19 20   11 12 13 14 15 16 17    9 10 11 12 13 14 15
# 22 23 24 25 26 27 28   19 20 21 22 23 24 25   16 17 18 19 20 21 22   21 22 23 24 25 26 27   18 19 20 21 22 23 24   16 17 18 19 20 21 22
# 29 30 31               26 27 28 29 30 31      23 24 25 26 27 28 29   28 29 30 31            25 26 27 28 29 30      23 24 25 26 27 28 29

```

**Remark:** The command used above has the same effect as `calendar-year(per-row=>6)`.
I.e. the first, year argument can be `Whatever` and the current year be "deduced" as `Date.today.year`.

### Specific year-month pairs

```
calendar([2022=>2, 2023=>11, 2024 => 2])

```

```
# February               November               February
# Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su   Mo Tu We Th Fr Sa Su
#     1  2  3  4  5  6          1  2  3  4  5             1  2  3  4
#  7  8  9 10 11 12 13    6  7  8  9 10 11 12    5  6  7  8  9 10 11
# 14 15 16 17 18 19 20   13 14 15 16 17 18 19   12 13 14 15 16 17 18
# 21 22 23 24 25 26 27   20 21 22 23 24 25 26   19 20 21 22 23 24 25
# 28                     27 28 29 30            26 27 28 29

```

### Month dataset

Using month dataset allows of utilizing HTML formatting in Markdown files or Jupyter notebooks.

Here is an example using ["Data::Translators"](https://raku.land/zef:antononcube/Data::Translators), [AAp2]:

```
use Data::Translators;
my $m = 'February';
my $res = to-html(calendar-month-dataset(2024, $m), field-names => calendar-weekday-names);
'<h4>' ~ $m ~ '</h4>' ~ $res.subst('<td>7</td>', '<td><span style="color: red"><b>7</b></span></td>')

```

#### February

| Mo | Tu | We | Th | Fr | Sa | Su |
| --- | --- | --- | --- | --- | --- | --- |
|  |  |  | 1 | 2 | 3 | 4 |
| 5 | 6 | **7** | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 |  |  |  |

**Remark:** The package ["Markup::Calendar"](https://raku.land/zef:antononcube/Markup::Calendar), [AAp1],
provides extensions of "Text::Calendar" for getting calendars in HTML and Markdown formats.

---

## Implementation notes

The initial codes for `calendar-month-block` and `calendar` were taken from <https://rosettacode.org/wiki/Calendar#Raku> .

The modifications done are for:

* Different signatures for making calendars
* Using of specs that are lists of year-month pairs
* Have the transposed, `ncal` style layout

Significant modifications are expected for calendars based on ranges of days.
(The lists can be both dense or sparse.)

---

## TODO

* Features
  * DONE Month block string
  * DONE Yearly calendar
  * DONE Calendar for span of months
    * I.e. "Emacs style"
  * DONE Calendar for a spec that is a list of year-month pairs
  * TODO Sparse calendar
    * Only for specified days
    * Days are specified with a list
  * DONE transposed or `ncal` mode
  * DONE Month block dataset
  * TODO Language localization
    * Using the short names of weekdays in "Date::Names", [TBp2]
    * Specified first day of week (e.g. Monday, not Sunday)
  * TODO Make sure month blocks align in multi-row layouts
    * Like, year calendars
    * For transposed only
  * TODO Return a list of pairs with year-month keys and month-text-block keys
    * Using adverb `:pairs`
* Unit tests
  * DONE Sanity / signatures
  * TODO Correctness
    * Monthly
    * Yearly
    * Span
* Documentation
  * DONE Basic README
  * DONE Detailed usage messages
  * TODO Comparison with LLMs

---

## References

[AAp1] Anton Antonov,
[Markup::Calendar Raku package](https://github.com/antononcube/Raku-Markup-Calendar),
(2024),
[GitHub/antononcube](https://github.com/antononcube).

[AAp2] Anton Antonov,
[Data::Translators Raku package](https://github.com/antononcube/Raku-Data-Translators),
(2023),
[GitHub/antononcube](https://github.com/antononcube).

[TBp1] Tom Browder,
[Calendar Raku package](https://github.com/tbrowder/Calendar),
(2020-2024),
[GitHub/tbrowder](https://github.com/tbrowder).

[TBp2] Tom Browder,
[Date::Names Raku package](https://github.com/tbrowder/Date-Names),
(2019-2024),
[GitHub/tbrowder](https://github.com/tbrowder).

[WCp1] Will Coleda,
[App::Cal Raku packate](https://github.com/coke/raku-cal),
(2022-2024),
[GitHub/coke](https://github.com/coke).


## dist_github-FCO-ProblemSolver.md
[![Build Status](https://travis-ci.org/FCO/ProblemSolver.svg?branch=master)](https://travis-ci.org/FCO/ProblemSolver)

# ProblemSolver

```
use ProblemSolver;
my ProblemSolver $problem .= new;

$problem.add-variable: "a", ^100;
$problem.add-variable: "b", ^100;

$problem.add-constraint: -> :$a!, :$b! {$a * 3 == $b + 14};
$problem.add-constraint: -> :$a!, :$b! {$a * 2 == $b};

say $problem.solve						# ((a => 14 b => 28))

```

```
# SEND + MORE = MONEY

use ProblemSolver;
my ProblemSolver $problem .= new: :stop-on-first-solution;

$problem.add-variable: "S", 1 ..^ 10;
$problem.add-variable: "E", ^10;
$problem.add-variable: "N", ^10;
$problem.add-variable: "D", ^10;
$problem.add-variable: "M", 1 ..^ 10;
$problem.add-variable: "O", ^10;
$problem.add-variable: "R", ^10;
$problem.add-variable: "Y", ^10;

$problem.unique-vars: <S E N D M O R Y>;
$problem.add-constraint: -> :$S!, :$E!, :$N!, :$D!, :$M!, :$O!, :$R!, :$Y! {
	note "$S$E$N$D + $M$O$R$E == $M$O$N$E$Y";

			   1000*$S + 100*$E + 10*$N + $D
	+		   1000*$M + 100*$O + 10*$R + $E
	==	10000*$M + 1000*$O + 100*$N + 10*$E + $Y
};

say $problem.solve
# You can wait for ever...

```

```
# 4 queens

use ProblemSolver;

class Point {
	has Int $.x;
	has Int $.y;

	method WHICH {
		"{self.^name}(:x($!x), :y($!y))"
	}
	method gist {$.WHICH}
}

sub MAIN(Int $n = 4) {
	my ProblemSolver $problem .= new: :stop-on-first-solution;

	sub print-board(%values) {
		my @board;
		for %values.kv -> $key, (:x($row), :y($col)) {
			@board[$row; $col] = $key;
		}
		for ^$n -> $row {
			for ^$n -> $col {
				if @board[$row; $col]:exists {
					print "● "
				} else {
					print "◦ "
				}
			}
			print "\n"
		}
		print "\n"
	}

	$problem.print-found = -> %values {
		print "\e[0;0H\e[0J";
		print-board(%values);
	}

	my @board = (^$n X ^$n).map(-> ($x, $y) {Point.new: :$x, :$y});
	my @vars = (1 .. $n).map: {"Q$_"};

	for @vars -> $var {
		$problem.add-variable: $var, @board;
	}

	$problem.unique-vars: @vars;

	$problem.constraint-vars: -> $q1, $q2 {
			$q1.x 			!= $q2.x
		&&	$q1.y			!= $q2.y
		&&	$q1.x - $q1.y	!= $q2.x - $q2.y
		&&	$q1.x + $q1.y	!= $q2.x + $q2.y
	}, @vars;

	my @response = $problem.solve;
	say "\n", "=" x 30, " Answers ", "=" x 30, "\n";

	for @response -> %ans {
		print-board(%ans)
	}
}

```

```
# colorize map

use ProblemSolver;
my ProblemSolver $problem .= new: :stop-on-first-solution;

my @colors = <green yellow blue white>;

my @states = <
	acre			alagoas
	amapa			amazonas
	bahia			ceara
	espirito-santo		goias
	maranhao		mato-grosso
	mato-grosso-do-sul	minas-gerais
	para			paraiba
	parana			pernambuco
	piaui			rio-de-janeiro
	rio-grande-do-norte	rio-grande-do-sul
	rondonia		roraima
	santa-catarina		sao-paulo
	sergipe			tocantins
>;

for @states -> $state {
	$problem.add-variable: $state, @colors;
}

$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <acre amazonas>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas roraima>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas rondonia>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <amazonas para>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para amapa>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para tocantins>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para mato-grosso>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <para maranhao>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <maranhao tocantins>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <maranhao piaui>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui ceara>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui pernambuco>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <piaui bahia>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara rio-grande-do-norte>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara paraiba>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <ceara pernambuco>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-grande-do-norte paraiba>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <pernambuco alagoas>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <alagoas sergipe>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sergipe bahia>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia minas-gerais>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia espirito-santo>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia tocantins>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <bahia goias>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso goias>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso tocantins>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso rondonia>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso mato-grosso-do-sul>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul goias>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul minas-gerais>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul sao-paulo>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <mato-grosso-do-sul parana>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sao-paulo minas-gerais>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <sao-paulo rio-de-janeiro>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-de-janeiro espirito-santo>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <rio-de-janeiro minas-gerais>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <minas-gerais espirito-santo>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <parana santa-catarina>;
$problem.constraint-vars: -> $color1, $color2 { $color1 !eq $color2 }, <santa-catarina rio-grande-do-sul>;

my %res = $problem.solve.first;
my $size = %res.keys.map(*.chars).max;
for %res.kv -> $state, $color {
	printf "%{$size}s => %s\n", $state, $color;
}

```


## dist_zef-raku-community-modules-Math-Random.md
[![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions) [![Actions Status](https://github.com/raku-community-modules/Math-Random/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/Math-Random/actions)

# NAME

Math::Random - Random numbers à la java.util.Random

## Background

I was bothered by Rakus's primitive random number handling (only `rand` and `srand`, with no mechanism to have multiple generators in parallel), so, instead of bugging some random people about it, I decided to write a module!

# SYNOPSIS

```
use Math::Random::JavaStyle; # uses same mechanics as
                             # java.util.Random
my $j = Math::Random::JavaStyle.new;
$j.setSeed(9001);
say $j.nextInt;
say $j.nextLong;
say $j.nextDouble;
say $j.nextInt(100);
say $j.nextLong(100_000_000_000);
say $j.nextDouble(100);
say $j.nxt(256); # generate a random 256-bit integer
say $j.nextGaussian;

use Math::Random::MT;
my $m64 = Math::Random::MT.mt19937_64;
#...

```

# DESCRIPTION

Math::Random provides a `Math::Random` role, and two classes using this role: `Math::Random::JavaStyle` (which uses the same mechanics as `java.util.Random`), and `Math::Random::MT` (which provides a mersenne twister with a long period of 219937 – 1).

# USAGE

The `Math::Random` role requires two methods to be implemented:

```
method setSeed(Int:D $seed --> Nil) { ... }
method nxt(Int:D $bits --> Int:D) { ... }

```

Unlike in Java's equivalent, `nxt` is required to accept as large of an input as possible.

# METHODS

## setSeed(Int $seed)

Sets the random seed.

## nextInt

Returns a random unsigned 32-bit integer.

## nextInt(Int $max)

Returns a random nonnegative integer less than `$max`.

The upper bound must not exceed `2**32`.

## nextLong

Returns a random unsigned 64-bit integer.

## nextLong(Int $max)

Returns a random nonnegative integer less than `$max`.

The upper bound must not exceed `2**64`.

## nextBoolean

Returns `True` or `False`.

## nextDouble

Returns a random `Num` in the range [0.0, 1.0).

## nextDouble(Num $max)

Returns a random `Num` in the range [0.0, `$max`).

## nextGaussian

Returns a random value according to the normal distribution.

## nxt(Int $bits)

Returns a random integer with `$bits` bits.

# ACKNOWLEDGEMENTS

Oracle's documentation on `java.util.Random`, as well as Wikipedia's article on the Mersenne Twister generator.

# TODO

* Provide constructors that also set the seed.
* Ensure thread safety, or create a thread-safe wrapper
* Provide higher-level methods
* Tests? They won't be easy to pull off, so if anyone wants to PR...

# AUTHORS

* +merlan #flirora
* Raku Community

# COPYRIGHT AND LICENSE

Copyright 2015 - 2017 +merlan #flirora

Copyright 2024 Raku Commuity

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_zef-raku-community-modules-Template6.md
[![Actions Status](https://github.com/raku-community-modules/Template6/actions/workflows/test.yml/badge.svg)](https://github.com/raku-community-modules/Template6/actions)

# NAME

Template6 - A Template Engine for Raku

# SYNOPSIS

```
use Template6;

```

# DESCRIPTION

Inspired by Template Toolkit from Perl, Template6 is a simple template engine designed to be a content-neutral template language.

This project does not intend to create an exact clone of Template Toolkit. Some features from TT are not planned for inclusion, and likewise, some feature will be included that are not in TT. Not all features will work the same either.

## Currently implemented features

### GET and SET statements, including implicit versions.

* [% get varname %]
* [% varname %]
* [% set varname = value %]
* [% varname = value %]

### FOR statement.

This replaces the FOREACH statement in TT2. It can be used in one of four ways:

* [% for listname as itemname %]
* [% for listname -> itemname %]
* [% for itemname in listname %]
* [% for itemname = listname %]

If used with Hashes, you'll need to query the .key or .value accessors.

### IF/ELSIF/ELSE/UNLESS statements.

These are very simplistic at the moment, but work for basic tests.

* Querying nested data structures using a simple dot operator syntax.
* CALL and DEFAULT statements.
* INSERT, INCLUDE and PROCESS statements.

## Differences with Template Toolkit

* You should use explicit quotes, including in INSERT/INCLUDE/PROCESS directives.
* UNLESS-ELSE is not supported - Raku also doesn't support this syntax
* All statement directives are case insensitive.
* There are no plans for the INTERPOLATE option/style.
* Anything not yet implemented (see TODO below.)

## Caveats

* Whitespace control is not implemented, so some things are fairly odd. See TODO.
* A lot of little nit-picky stuff, likely related to the whitespace issue.

## TODO

### Short Term Goals

* WRAPPER statement
* block statements
* given/when statements
* Add 'absolute' and 'relative' options to Template6::Provider::File
* Whitespace control
* Precompiled/cached templates
* Tag styles (limited to definable start\_tag and end\_tag)

### Long Term Goals

* Filters
* Variable interpolation (in strings, variable names, etc.)
* Capture of directive output
* Directive comments
* Side-effect notation
* Multiple directives in a single statement tag set
* Macros, plugins, etc.

## Possible future directions

I would also like to investigate the potential for an alternative to Template6::Parser that generates Raku closures without the use of EVAL. This would be far trickier, and would not be compatible with the precompiled templates, but would be an interesting exercise nonetheless.

# AUTHOR

Timothy Totten

# COPYRIGHT AND LICENSE

Copyright 2012 - 2017 Timothy Totten

Copyright 2018 - 2023 Raku Community

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## signatures.md
## Chunk 1 of 2
Signature literals

A guide to signatures in Raku

[`Signatures`](/type/Signature) appear inside parentheses after [subroutine](/type/Sub) and [method](/type/Method) names, on blocks after a `->` or `<->` arrow, as the input to [variable declarators](/language/variables#Variable_declarators_and_scope) like [`my`](/syntax/my), or as a separate term starting with a colon.

```raku
sub f($x) { }
#    ^^^^ Signature of sub f
my method x() { }
#          ^^ Signature of a method
my $s = sub (*@a) { }
#           ^^^^^ Signature of an anonymous function

for <a b c> -> $x { }
#              ^^   Signature of a Block

my ($a, @b) = 5, (6, 7, 8);
#  ^^^^^^^^ Signature of a variable declarator

my $sig = :($a, $b);
#          ^^^^^^^^ Standalone Signature object
```

Signature literals can be used to define the signature of a callback or a closure.

```raku
sub f(&c:(Int)) { }
sub will-work(Int) { }
sub won't-work(Str) { }
f(&will-work);

f(&won't-work);
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '&c'␤»

f(-> Int { 'this works too' } );
```

You can use any kind of literal, including numeric ones, as part of a signature; this is generally used in conjunction with multis

```raku
proto stuff(|) {*}
multi stuff(33) { 58 }
multi stuff(⅓) { 43 }
multi stuff(Int)  { 3 }
multi stuff(Complex)  { 66 }
say stuff($_) for (33, ⅓, i, 48); # OUTPUT: «58␤43␤66␤3␤»

```

However, you can't use `True` or `False` as literals in signatures since they will always succeed (or fail). A warning will be issued if you do so:

```raku
sub foo(True) {};
my $sig =  :( True );

```

They will both warn "Literal values in signatures are smartmatched against and smartmatch with `True` will always succeed. Use the `where` clause instead.". Use of `False` will produce a similar warning.

Smartmatching signatures against a [`List`](/type/List) is supported.

```raku
my $sig = :(Int $i, Str $s);
say (10, 'answer') ~~ $sig;
# OUTPUT: «True␤»
my $sub = sub ( Str $s, Int $i ) { return $s xx $i };
say $sub.signature ~~ :( Str, Int );
# OUTPUT: «True␤»
given $sig {
    when :(Str, Int) { say 'mismatch' }
    when :($, $)     { say 'match' }
    default          { say 'no match' }
}
# OUTPUT: «match␤»
```

It matches the second `when` clause since `:($, $)` represents a [`Signature`](/type/Signature) with two scalar, anonymous, arguments, which is a more general version of `$sig`.

When smartmatching against a [`Hash`](/type/Hash), the signature is assumed to consist of the keys of the [`Hash`](/type/Hash).

```raku
my %h = left => 1, right => 2;
say %h ~~ :(:$left, :$right);
# OUTPUT: «True␤»
```

[`Signature`](/type/Signature) literals can contain string/numeric literals

```raku
my $sig = :('Þor', Str, Int);
say <Þor Hammer 1> ~~ $sig; # OUTPUT: «True␤»
```

And they can also contain the invocant marker

```raku
class Foo {
    method bar( $self: ){ "baz" }
};
say Foo.^methods.first(*.name eq 'bar').signature ~~ :($: *%) ;
# OUTPUT: «True␤»
```

# [Parameter separators](#Signature_literals "go to top of document")[§](#Parameter_separators "direct link")

A signature consists of zero or more [`Parameter`](/type/Parameter)s, separated by commas.

```raku
my $sig = :($a, @b, %c);
sub add($a, $b) { $a + $b };
```

As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method. This is done in order to distinguish it from what would then be a regular positional parameter. The invocant is the object that was used to call the method, which is usually bound to [`self`](/routine/self). By specifying it in the signature, you can change the variable name it is bound to.

```raku
method ($a: @b, %c) {};       # first argument is the invocant

class Foo {
    method whoami($me:) {
        "Well I'm class $me.^name(), of course!"
    }
}
say Foo.whoami; # OUTPUT: «Well I'm class Foo, of course!␤»
```

# [Type constraints](#Signature_literals "go to top of document")[§](#Type_constraints "direct link")

Parameters can optionally have a type constraint (the default is [`Any`](/type/Any)). These can be used to restrict the allowed input to a function.

```raku
my $sig = :(Int $a, Str $b);

```

Type constraints can have any compile-time defined value

```raku
subset Positive-integer of Int where * > 0;
sub divisors(Positive-integer $n) { $_ if $n %% $_ for 1..$n };
CATCH { default { put .^name, ': ', .Str; .resume } };

divisors 2.5;
# OUTPUT: «X::TypeCheck::Binding::Parameter: Type check failed in binding to parameter '$n'; expected Positive-integer but got Rat (2.5)␤»

divisors -3;
# OUTPUT: «X::TypeCheck::Binding::Parameter: Constraint type check failed in binding to parameter '$n'; expected Positive-integer but got Int (-3)␤»

```

Please note that in the code above type constraints are enforced at two different levels: the first level checks if it belongs to the type in which the subset is based, in this case [`Int`](/type/Int). If it fails, a `Type check` error is produced. Once that filter is cleared, the constraint that defined the subset is checked, producing a `Constraint type check` error if it fails.

Type constraints can define multiple allowable types

```raku
sub abbrev($arg where Str|List|Hash) {...} # throws if $arg is not one of those types

```

Anonymous arguments are fine too, if you don't actually need to refer to a parameter by name, for instance to distinguish between different signatures in a [multi](/language/functions#Multi-dispatch) or to check the signature of a [`Callable`](/type/Callable).

```raku
my $sig = :($, @, %a);          # two anonymous and a "normal" parameter
$sig = :(Int, Positional);      # just a type is also fine (two parameters)
sub baz(Str) { "Got passed a Str" }

```

Type constraints may also be [type captures](/language/signatures#Type_captures).

In addition to those *nominal* types, additional constraints can be placed on parameters in the form of code blocks which must return a true value to pass the type check

```raku
sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { }
```

The code in `where` clauses has some limitations: anything that produces side-effects (e.g., printing output, pulling from an iterator, or increasing a state variable) is not supported and may produce surprising results if used. Also, the code of the `where` clause may run more than once for a single typecheck in some implementations.

The `where` clause doesn't need to be a code block, anything on the right of the `where`-clause will be used to [smartmatch](/language/operators#infix_~~) the argument against it. So you can also write:

```raku
multi factorial(Int $ where 0) { 1 }
multi factorial(Int $x)        { $x * factorial($x - 1) }
```

The first of those can be shortened to

```raku
multi factorial(0) { 1 }
```

i.e., you can use a literal directly as a type and value constraint on an anonymous parameter.

**Tip:** pay attention to not accidentally leave off a block when you, say, have several conditions:

```raku
-> $y where   .so && .name    {}( sub one   {} ); # WRONG!!
-> $y where { .so && .name }  {}( sub two   {} ); # OK!
-> $y where   .so &  .name.so {}( sub three {} ); # Also good
```

The first version is wrong and will issue a warning about a sub object coerced to string. The reason is the expression is equivalent to `($y ~~ ($y.so && $y.name))`; that is "call `.so`, and if that is `True`, call `.name`; if that is also `True` use its value for smartmatching…". It's the **result** of `(.so && .name)` it will be smartmatched against, but we want to check that both `.so` and `.name` are truthy values. That is why an explicit Block or a [`Junction`](/type/Junction) is the right version.

All previous arguments that are not part of a sub-signature in a [`Signature`](/type/Signature) are accessible in a `where`-clause that follows an argument. Therefore, the `where`-clause of the last argument has access to all arguments of a signature that are not part of a sub-signature. For a sub-signature place the `where`-clause inside the sub-signature.

```raku
sub foo($a, $b where * == $a ** 2) { say "$b is a square of $a" }
foo 2, 4; # OUTPUT: «4 is a square of 2␤»»
# foo 2, 3;
# OUTPUT: «Constraint type check failed in binding to parameter '$b'…»
```

## [Constraining optional arguments](#Signature_literals "go to top of document")[§](#Constraining_optional_arguments "direct link")

[Optional arguments](#Optional_and_mandatory_arguments) can have constraints, too. Any `where` clause on any parameter will be executed, even if it's optional and not provided by the caller. In that case you may have to guard against undefined values within the `where` clause.

```raku
sub f(Int $a, UInt $i? where { !$i.defined or $i > 5 }) { ... }
```

## [Constraining slurpy arguments](#Signature_literals "go to top of document")[§](#Constraining_slurpy_arguments "direct link")

[Slurpy arguments](#Slurpy_parameters) can not have type constraints. A `where`-clause in conjunction with a [`Junction`](/type/Junction) can be used to that effect.

```raku
sub f(*@a where {$_.all ~~ Int}) { say @a };
f(42);
f(<a>);
CATCH { default { say .^name, ' ==> ', .Str }  }
# OUTPUT: «[42]␤Constraint type check failed in binding to parameter '@a' ...»

```

## [Constraining named arguments](#Signature_literals "go to top of document")[§](#Constraining_named_arguments "direct link")

Constraints against [named arguments](#Positional_vs._named_arguments) apply to the value part of the [colon-pair](/type/Pair).

```raku
sub f(Int :$i){};
f :i<forty-two>;
CATCH { default { say .^name, ' ==> ', .Str }  }
# OUTPUT: «X::TypeCheck::Binding::Parameter ==> Type check failed in
# binding to parameter '$i'; expected Int but got Str ("forty-two")␤»
```

## [Constraining argument definiteness](#Signature_literals "go to top of document")[§](#Constraining_argument_definiteness "direct link")

Normally, a type constraint only checks whether the value of the parameter is of the correct type. Crucially, both *object instances* and *type objects* will satisfy such a constraint as illustrated below:

```raku
say  42.^name;    # OUTPUT: «Int␤»
say  42 ~~ Int;   # OUTPUT: «True␤»
say Int ~~ Int;   # OUTPUT: «True␤»
```

Note how both `42` and [`Int`](/type/Int) satisfy the match.

Sometimes we need to distinguish between these object instances (`42`) and type objects ([`Int`](/type/Int)). Consider the following code:

```raku
sub limit-lines(Str $s, Int $limit) {
    my @lines = $s.lines;
    @lines[0 .. min @lines.elems, $limit].join("\n")
}
say (limit-lines "a \n b \n c \n d \n", 3).raku; # "a \n b \n c \n d "
say limit-lines Str, 3;
CATCH { default { put .^name, ': ', .Str } };
# OUTPUT: «X::Multi::NoMatch: Cannot resolve caller lines(Str: );
# none of these signatures match:
#     (Str:D $: :$count!, *%_)
#     (Str:D $: $limit, *%_)
#     (Str:D $: *%_)»
say limit-lines "a \n b", Int; # Always returns the max number of lines
```

Here we really only want to deal with string instances, not type objects. To do this, we can use the `:D` type constraint. This constraint checks that the value passed is an *object instance*, in a similar fashion to calling its [DEFINITE](/language/mop#DEFINITE) (meta)method.

To warm up, let's apply `:D` to the right-hand side of our humble [`Int`](/type/Int) example:

```raku
say  42 ~~ Int:D;  # OUTPUT: «True␤»
say Int ~~ Int:D;  # OUTPUT: «False␤»
```

Note how only `42` matches `Int:D` in the above.

Returning to `limit-lines`, we can now amend its signature to catch the error early:

```raku
sub limit-lines(Str:D $s, Int $limit) { };
say limit-lines Str, 3;
CATCH { default { put .^name ~ '--' ~ .Str } };
# OUTPUT: «Parameter '$s' of routine 'limit-lines' must be an object instance of type 'Str',
#          not a type object of type 'Str'.  Did you forget a '.new'?»
```

This is much better than the way the program failed before, since here the reason for failure is clearer.

It's also possible that *type objects* are the only ones that make sense for a routine to accept. This can be done with the `:U` type constraint, which checks whether the value passed is a type object rather than an object instance. Here's our [`Int`](/type/Int) example again, this time with `:U` applied:

```raku
say  42 ~~ Int:U;  # OUTPUT: «False␤»
say Int ~~ Int:U;  # OUTPUT: «True␤»
```

Now `42` fails to match `Int:U` while [`Int`](/type/Int) succeeds.

Here's a more practical example:

```raku
sub can-turn-into(Str $string, Any:U $type) {
   return so $string.$type;
}
say can-turn-into("3", Int);        # OUTPUT: «True␤»
say can-turn-into("6.5", Int);      # OUTPUT: «True␤»
say can-turn-into("6.5", Num);      # OUTPUT: «True␤»
say can-turn-into("a string", Num); # OUTPUT: «False␤»
```

Calling `can-turn-into` with an object instance as its second parameter will yield a constraint violation as intended:

```raku
say can-turn-into("a string", 123);
# OUTPUT: «Parameter '$type' of routine 'can-turn-into' must be a type object
# of type 'Any', not an object instance of type 'Int'...»

```

For explicitly indicating the normal behavior, that is, not constraining whether the argument will be an instance or a type object, `:_` can be used but this is unnecessary since this is the default constraint (of this kind) on arguments. Thus, `:(Num:_ $)` is the same as `:(Num $)`.

To recap, here is a quick illustration of these type constraints, also known collectively as *type smileys*:

```raku
# Checking a type object
say Int ~~ Any:D;    # OUTPUT: «False␤»
say Int ~~ Any:U;    # OUTPUT: «True␤»
say Int ~~ Any:_;    # OUTPUT: «True␤»

# Checking a subset
subset Even of Int where * // 2;
say 3 ~~ Even:D;     # OUTPUT: «True␤»
say 3 ~~ Even:U;     # OUTPUT: «False␤»
say Int ~~ Even:U;   # OUTPUT: «True␤»

# Checking an object instance
say 42 ~~ Any:D;     # OUTPUT: «True␤»
say 42 ~~ Any:U;     # OUTPUT: «False␤»
say 42 ~~ Any:_;     # OUTPUT: «True␤»

# Checking a user-supplied class
class Foo {};
say Foo ~~ Any:D;    # OUTPUT: «False␤»
say Foo ~~ Any:U;    # OUTPUT: «True␤»
say Foo ~~ Any:_;    # OUTPUT: «True␤»

# Checking an instance of a class
my $f = Foo.new;
say $f  ~~ Any:D;    # OUTPUT: «True␤»
say $f  ~~ Any:U;    # OUTPUT: «False␤»
say $f  ~~ Any:_;    # OUTPUT: «True␤»
```

The [Classes and Objects](/language/classtut) document further elaborates on the concepts of instances and type objects and discovering them with the `.DEFINITE` method.

Keep in mind all parameters have values; even optional ones have default values that are the type object of the constrained type for explicit type constraints. If no explicit type constraint exists, the default value is an [`Any`](/type/Any) type object for methods, submethods, and subroutines, and a [`Mu`](/type/Mu) type object for blocks. This means that if you use the `:D` type smiley, you'd need to provide a default value or make the parameter required. Otherwise, the default value would be a type object, which would fail the definiteness constraint.

```raku
sub divide (Int:D :$a = 2, Int:D :$b!) { say $a/$b }
divide :1a, :2b; # OUTPUT: «0.5␤»
```

The default value will kick in when that particular parameter, either positional or named, gets no value *at all*.

```raku
sub f($a = 42){
  my $b is default('answer');
  say $a;
  $b = $a;
  say $b
};
f;     # OUTPUT: «42␤42␤»
f Nil; # OUTPUT: «Nil␤answer␤»
```

`$a` has 42 as its default value. With no value, `$a` will be assigned the default value declared in the [`Signature`](/type/Signature). However, in the second case, it *does* receive a value, which happens to be [`Nil`](/type/Nil). Assigning [`Nil`](/type/Nil) to any variable resets it to its default value, which has been declared as `'answer'` by use of the *default* trait. That explains what happens the second time we call `f`. Routine parameters and variables deal differently with default value, which is in part clarified by the different way default values are declared in each case (using `=` for parameters, using the `default` trait for variables).

Note: in 6.c language, the default value of `:U`/`:D` constrained variables was a type object with such a constraint, which is not initializable, thus you cannot use the `.=` operator, for example.

```raku
use v6.c;
my Int:D $x .= new: 42;
# OUTPUT: You cannot create an instance of this type (Int:D)
# in block <unit> at -e line 1

```

In the 6.d language, the default *default* is the type object without the smiley constraint:

```raku
use v6.d;
my Int:D $x .= new: 42; # OUTPUT: «42␤»

```

A closing remark on terminology: this section is about the use of the type smileys `:D` and `:U` to constrain the definiteness of arguments. Occasionally *definedness* is used as a synonym for *definiteness*; this may be confusing, since the terms have subtly different meanings.

As explained above, *definiteness* is concerned with the distinction between type objects and object instances. A type object is always indefinite, while an object instance is always definite. Whether an object is a type object/indefinite or an object instance/definite can be verified using the [DEFINITE](/language/mop#DEFINITE) (meta)method.

*Definiteness* should be distinguished from *definedness*, which is concerned with the difference between defined and undefined objects. Whether an object is defined or undefined can be verified using the `defined`-method, which is implemented in class [`Mu`](/type/Mu). By default a type object is considered undefined, while an object instance is considered defined; that is: `.defined` returns `False` on a type object, and `True` otherwise. But this default behavior may be overridden by subclasses. An example of a subclass that overrides the default `.defined` behavior is [`Failure`](/type/Failure), so that even an instantiated [`Failure`](/type/Failure) acts as an undefined value:

```raku
my $a = Failure;                # Initialize with type object
my $b = Failure.new("foo");     # Initialize with object instance
say $a.DEFINITE;                # OUTPUT: «False␤» : indefinite type object
say $b.DEFINITE;                # OUTPUT: «True␤»  : definite object instance
say $a.defined;                 # OUTPUT: «False␤» : default response
say $b.defined;                 # OUTPUT: «False␤» : .defined override
```

## [Constraining signatures of](#Signature_literals "go to top of document") [`Callable`](/type/Callable)s[§](#Constraining_signatures_of_Callables "direct link")

:u

whitespace allowed):

```raku
sub apply(&l:(Int:D --> Int:D), Int:D \n) {
    l(n)
}

sub identity(Int:D \i --> Int:D) { i }
sub double(Int:D \x --> Int:D) { 2 * x }

say apply &identity, 10; # OUTPUT: «10␤»
say apply &double, 10;   # OUTPUT: «20␤»
```

Typed [lambdas](/language/functions#Blocks_and_lambdas) also work with constrained callable parameters.

```raku
say apply -> Int:D \x --> Int:D { 2 * x }, 3;  # OUTPUT: «6␤»
say apply -> Int:D \x --> Int:D { x ** 3 }, 3; # OUTPUT: «27␤»

```

Note that this shorthand syntax is available only for parameters with the `&` sigil. For others, you need to use the long version:

```raku
sub play-with-tens($c where .signature ~~ :(Int, Str)) { say $c(10, 'ten') }
sub by-joining-them(Int $i, Str $s) { $s ~ $i }
play-with-tens &by-joining-them;                              # OUTPUT: «ten10␤»
play-with-tens -> Int \i, Str \s { s x (1..10).roll mod i };  # OUTPUT: «tenten␤»

sub g(Num $i, Str $s) { $s ~ $i }
# play-with-tens(&g); # Constraint type check failed
```

## [Constraining return types](#Signature_literals "go to top of document")[§](#Constraining_return_types "direct link")

There are multiple ways to constrain return types on a [`Routine`](/type/Routine). All versions below are currently valid and will force a type check on successful execution of a routine.

[`Nil`](/type/Nil) and [`Failure`](/type/Failure) are always allowed as return types, regardless of any type constraint. This allows [`Failure`](/type/Failure) to be returned and passed on down the call chain.

```raku
sub foo(--> Int) { Nil };
say foo.raku; # OUTPUT: «Nil␤»
```

Type captures are not supported.

### [Return type arrow: `--`>](#Signature_literals "go to top of document")[§](#Return_type_arrow:_--> "direct link")

This form of indicating return types (or constants) in the signature is preferred, since it can handle constant values while the others can't. For consistency, it is the only form accepted on this site.

The return type arrow has to be placed at the end of the parameter list, with or without a `,` before it.

```raku
sub greeting1(Str $name  --> Str) { say "Hello, $name" } # Valid
sub greeting2(Str $name, --> Str) { say "Hello, $name" } # Valid

sub favorite-number1(--> 42) {        } # OUTPUT: 42
sub favorite-number2(--> 42) { return } # OUTPUT: 42

```

If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless.

```raku
sub foo(Str $word --> 123) { say $word; return; }
my $value = foo("hello"); # OUTPUT: hello
say $value;               # OUTPUT: 123

```

```raku
# The code below will not compile
sub foo(Str $word --> 123) { say $word; return $word; }
my $value = foo("hello");
say $value;

```

### [`returns`](#Signature_literals "go to top of document")[§](#returns "direct link")

The keyword `returns` following a signature declaration has the same function as `-->` with the caveat that this form does not work with constant values. You cannot use it in a block either. That is why the pointy arrow form is always preferred.

```raku
sub greeting(Str $name) returns Str { say "Hello, $name" } # Valid

```

```raku
sub favorite-number returns 42 {        } # This will fail.

```

### [`of`](#Signature_literals "go to top of document")[§](#of "direct link")

`of` is just the real name of the `returns` keyword.

```raku
sub foo() of Int { 42 }; # Valid

```

```raku
sub foo() of 42 {  };    # This will fail.

```

### [prefix(C-like) form](#Signature_literals "go to top of document")[§](#prefix(C-like)_form "direct link")

This is similar to placing type constraints on variables like `my Type $var = 20;`, except the `$var` is a definition for a routine.

```raku
my Int sub bar { 1 };     # Valid

```

```raku
my 42 sub bad-answer {};  # This will fail.

```

## [Coercion type](#Signature_literals "go to top of document")[§](#Coercion_type "direct link")

To accept one type but coerce it automatically to another, use the accepted type as an argument to the target type. If the accepted type is [`Any`](/type/Any) it can be omitted.

```raku
sub f(Int(Str) $want-int, Str() $want-str) {
    say $want-int.^name ~ ' ' ~ $want-str.^name
}
f '10', 10;
# OUTPUT: «Int Str␤»

sub foo(Date(Str) $d) { say $d.^name; say $d };
foo "2016-12-01";
# OUTPUT: «Date␤2016-12-01␤»
```

The coercion is performed by calling the method with the name of the type to coerce to, if it exists. In this example, we're calling the builtin method [`Date`](/type/Date) on the [`Str`](/type/Str) class. The method is assumed to return the correct type—no additional checks on the result are currently performed.

Coercion can also be performed on return types:

```raku
sub square-str (Int $x --> Str(Int)) {
    $x²
}

for 2,4, *²  … 256 -> $a {
    say $a, "² is ", square-str( $a ).chars, " figures long";
}

# OUTPUT: «2² is 1 figures long␤
#          4² is 2 figures long␤
#          16² is 3 figures long␤
#          256² is 5 figures long␤»

```

In this example, coercing the return type to [`Str`](/type/Str) allows us to directly apply string methods, such as the number of characters.

**Note**: The appropriate method must be available on the argument, so be careful when trying to coerce custom types.

```raku
class Foo { }

sub bar(Foo(Int) $x) { say $x }

bar(3);
# OUTPUT: «Impossible coercion from 'Int' into 'Foo': no acceptable coercion method found␤»

```

# [Slurpy parameters](#Signature_literals "go to top of document")[§](#Slurpy_parameters "direct link")

A function is variadic if it can take a varying number of arguments; that is, its arity is not fixed. Therefore, [optional](/language/signatures#Optional_and_mandatory_arguments), named, and slurpy parameters make routines that use them *variadic*, and by extension are called variadic arguments. Here we will focus on slurpy parameters, or simply *slurpies*.

An array or hash parameter can be marked as *slurpy* by leading single (\*) or double asterisk (\*\*) or a leading plus (+). A slurpy parameter can bind to an arbitrary number of arguments (zero or more), and it will result in a type that is compatible with the sigil.

These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles.

```raku
my $sig1 = :($a, @b);  # exactly two arguments, second must be Positional
my $sig2 = :($a, *@b); # at least one argument, @b slurps up any beyond that
my $sig3 = :(*%h);     # no positional arguments, but any number
                       # of named arguments

sub one-arg (@)  { }
sub slurpy  (*@) { }
one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7))
slurpy  (5, 6, 7); # ok
slurpy   5, 6, 7 ; # ok
# one-arg(5, 6, 7) ; # X::TypeCheck::Argument
# one-arg  5, 6, 7 ; # X::TypeCheck::Argument

sub named-names (*%named-args) { %named-args.keys };
say named-names :foo(42) :bar<baz>; # OUTPUT: «foo bar␤»

```

Positional and named slurpies can be combined; named arguments (i.e., [`Pair`](/type/Pair)s) are collected in the specified hash, positional arguments in the array:

```raku
sub combined-slurpy (*@a, *%h) { { array => @a, hash => %h } }
# or: sub combined-slurpy (*%h, *@a) { ... }

say combined-slurpy(one => 1, two => 2);
# OUTPUT: «{array => [], hash => {one => 1, two => 2}}␤»
say combined-slurpy(one => 1, two => 2, 3, 4);
# OUTPUT: «{array => [3 4], hash => {one => 1, two => 2}}␤»
say combined-slurpy(one => 1, two => 2, 3, 4, five => 5);
# OUTPUT: «{array => [3 4], hash => {five => 5, one => 1, two => 2}}␤»
say combined-slurpy(one => 1, two => 2, 3, 4, five => 5, 6);
# OUTPUT: «{array => [3 4 6], hash => {five => 5, one => 1, two => 2}}␤»

```

Note that positional parameters aren't allowed after slurpy (or, in fact, after any type of variadic) parameters:

```raku
:(*@args, $last);
# ===SORRY!=== Error while compiling:
# Cannot put required parameter $last after variadic parameters

```

Normally a slurpy parameter will create an [`Array`](/type/Array) (or compatible type), create a new [`Scalar`](/type/Scalar) container for each argument, and assign the value from each argument to those [`Scalar`](/type/Scalar)s. If the original argument also had an intermediary [`Scalar`](/type/Scalar) it is bypassed during this process, and is not available inside the called function.

Sigiled parameters will always impose a context on the collected arguments. Sigilless parameters can also be used slurpily, preceded by a + sign, to work with whatever initial type they started with:

```raku
sub zipi( +zape ) {
    zape.^name => zape
};
say zipi( "Hey "); # OUTPUT: «List => (Hey )␤»
say zipi( 1...* ); # OUTPUT: «Seq => (...)␤»

```

Slurpy parameters have special behaviors when combined with some [traits and modifiers](#Parameter_traits_and_modifiers), as described in [the section on slurpy array parameters](/language/signatures#Types_of_slurpy_array_parameters).

Methods automatically get a `*%_` slurpy named parameter added if they don't have another slurpy named parameter declared.

# [Types of slurpy array parameters](#Signature_literals "go to top of document")[§](#Types_of_slurpy_array_parameters "direct link")

There are three variations to slurpy array parameters.

* The single asterisk form flattens passed arguments.
* The double asterisk form does not flatten arguments.
* The plus form flattens according to the single argument rule.

Each will be described in detail in the next few sections. As the difference between each is a bit nuanced, examples are provided for each to demonstrate how each slurpy convention varies from the others.

## [Flattened slurpy](#Signature_literals "go to top of document")[§](#Flattened_slurpy "direct link")

Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare [`Iterable`](/type/Iterable)s.

```raku
my @array = <a b c>;
my $list := <d e f>;
sub a(*@a)  { @a.raku.say };
a(@array);                 # OUTPUT: «["a", "b", "c"]␤»
a(1, $list, [2, 3]);       # OUTPUT: «[1


## signatures.md
## Chunk 2 of 2
, "d", "e", "f", 2, 3]␤»
a([1, 2]);                 # OUTPUT: «[1, 2]␤»
a(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, 1, 2, 3, 4, 5]␤»
a(($_ for 1, 2, 3));       # OUTPUT: «[1, 2, 3]␤»

```

A single asterisk slurpy flattens all given iterables, effectively hoisting any object created with commas up to the top level.

## [Unflattened slurpy](#Signature_literals "go to top of document")[§](#Unflattened_slurpy "direct link")

Slurpy parameters declared with two stars do not flatten any [`Iterable`](/type/Iterable) arguments within the list, but keep the arguments more or less as-is:

```raku
my @array = <a b c>;
my $list := <d e f>;
sub b(**@b) { @b.raku.say };
b(@array);                 # OUTPUT: «[["a", "b", "c"],]␤»
b(1, $list, [2, 3]);       # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»
b([1, 2]);                 # OUTPUT: «[[1, 2],]␤»
b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
b(($_ for 1, 2, 3));       # OUTPUT: «[(1, 2, 3),]␤»

```

The double asterisk slurpy hides the nested comma objects and leaves them as-is in the slurpy array.

## [Single argument rule slurpy](#Signature_literals "go to top of document")[§](#Single_argument_rule_slurpy "direct link")

A slurpy parameter created using a plus engages the *"single argument rule"*, which decides how to handle the slurpy argument based upon context. Basically, if only a single argument is passed and that argument is [`Iterable`](/type/Iterable), that argument is used to fill the slurpy parameter array. In any other case, `+@` works like `**@`.

```raku
my @array = <a b c>;
my $list := <d e f>;
sub c(+@b) { @b.raku.say };
c(@array);                 # OUTPUT: «["a", "b", "c"]␤»
c(1, $list, [2, 3]);       # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]␤»
c([1, 2]);                 # OUTPUT: «[1, 2]␤»
c(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
c(($_ for 1, 2, 3));       # OUTPUT: «[1, 2, 3]␤»

```

For additional discussion and examples, see [Slurpy Conventions for Functions](/language/functions#Slurpy_conventions).

# [Type captures](#Signature_literals "go to top of document")[§](#Type_captures "direct link")

Type captures allow deferring the specification of a type constraint to the time the function is called. They allow referring to a type both in the signature and the function body.

```raku
sub f(::T $p1, T $p2, ::C){
    # $p1 and $p2 are of the same type T, that we don't know yet
    # C will hold a type we derive from a type object or value
    my C $division = $p1 / $p2;
    return sub (T $p1) {
        $division * $p1;
    }
}

# The first parameter is Int and so must be the 2nd.
# We derive the 3rd type from calling the operator that is used in &f.
my &s = f(10, 2, Int.new / Int.new);
say s(2); # 10 / 2 * 2 == 10
```

# [Positional vs. named arguments](#Signature_literals "go to top of document")[§](#Positional_vs._named_arguments "direct link")

An argument can be *positional* or *named*. By default, arguments are positional, except slurpy hash and arguments marked with a leading colon `:`. The latter is called a [colon-pair](/type/Pair). Check the following signatures and what they denote:

```raku
$sig1 = :($a);               # a positional argument
$sig2 = :(:$a);              # a named argument of name 'a'
$sig3 = :(*@a);              # a slurpy positional argument
$sig4 = :(*%h);              # a slurpy named argument

```

On the caller side, positional arguments are passed in the same order as the arguments are declared.

```raku
sub pos($x, $y) { "x=$x y=$y" }
pos(4, 5);                          # OUTPUT: «x=4 y=5»
```

In the case of named arguments and parameters, only the name is used for mapping arguments to parameters. If a fat arrow is used to construct a [`Pair`](/type/Pair) only those with valid identifiers as keys are recognized as named arguments.

```raku
sub named(:$x, :$y) { "x=$x y=$y" }
named( y => 5, x => 4);             # OUTPUT: «x=4 y=5»

```

You can invoke the routine using a variable with the same name as the named argument; in that case `:` will be used for the invocation so that the name of the variable is understood as the key of the argument.

```raku
sub named-shortcut( :$shortcut ) {
    say "Looks like $shortcut"
}
named-shortcut( shortcut => "to here"); # OUTPUT: «Looks like to here␤»
my $shortcut = "Þor is mighty";
named-shortcut( :$shortcut );           # OUTPUT: «Looks like Þor is mighty␤»
```

It is possible to have a different name for a named argument than the variable name:

```raku
sub named(:official($private)) { "Official business!" if $private }
named :official;
```

# [Argument aliases](#Signature_literals "go to top of document")[§](#Argument_aliases "direct link")

The [colon-pair](/type/Pair) syntax can be used to provide aliases for arguments:

```raku
sub alias-named(:color(:$colour), :type(:class($kind))) {
    say $colour ~ " " ~ $kind
}
alias-named(color => "red", type => "A");    # both names can be used
alias-named(colour => "green", type => "B"); # more than two names are ok
alias-named(color => "white", class => "C"); # every alias is independent
```

The presence of the colon `:` will decide whether we are creating a new named argument or not. `:$colour` will not only be the name of the aliased variable, but also a new named argument (used in the second invocation). However, `$kind` will just be the name of the aliased variable, that does not create a new named argument. More uses of aliases can be found in [sub MAIN](/language/create-cli#sub_MAIN).

A function with named arguments can be called dynamically, dereferencing a [`Pair`](/type/Pair) with `|` to turn it into a named argument.

```raku
multi f(:$named) { note &?ROUTINE.signature };
multi f(:$also-named) { note &?ROUTINE.signature };
for 'named', 'also-named' -> $n {
    f(|($n => rand))                # OUTPUT: «(:$named)␤(:$also-named)␤»
}

my $pair = :named(1);
f |$pair;                           # OUTPUT: «(:$named)␤»
```

The same can be used to convert a [`Hash`](/type/Hash) into named arguments.

```raku
sub f(:$also-named) { note &?ROUTINE.signature };
my %pairs = also-named => 4;
f |%pairs;                              # OUTPUT: «(:$also-named)␤»
```

A [`Hash`](/type/Hash) that contains a list may prove problematic when slipped into named arguments. To avoid the extra layer of containers coerce to [`Map`](/type/Map) before slipping.

```raku
class C { has $.x; has $.y; has @.z };
my %h = <x y z> Z=> (5, 20, [1,2]);
say C.new(|%h.Map);
# OUTPUT: «C.new(x => 5, y => 20, z => [1, 2])␤»
```

You can create as many aliases to a named argument as you want:

```raku
sub alias-named(:color(:$colour),
                :variety(:style(:sort(:type(:class($kind)))))) {
    return $colour ~ " " ~ $kind
}
say alias-named(color => "red", style => "A");
say alias-named(colour => "green", variety => "B");
say alias-named(color => "white", class => "C");

```

You can create named arguments that do not create any variables by making the argument an alias for an [anonymous argument](#index-entry-anonymous_arguments). This can be useful when using named arguments solely as a means of selecting a `multi` candidate, which is often the case with traits, for instance:

```raku
# Timestamps calls to a routine.
multi trait_mod:<is>(Routine:D $r is raw, :timestamped($)!) {
    $r does my role timestamped { has Instant:D @.timestamps };
    $r.wrap: -> | { ENTER $r.timestamps.push: now; callsame };
}

sub foo is timestamped { }
foo;
say +&foo.?timestamps; # OUTPUT: «1␤»

```

# [Optional and mandatory arguments](#Signature_literals "go to top of document")[§](#Optional_and_mandatory_arguments "direct link")

Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:

```raku
$sig1 = :(Str $id);         # required parameter
$sig2 = :($base = 10);      # optional parameter, default value 10
$sig3 = :(Int $x?);         # optional parameter, default is the Int type object

```

Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:

```raku
$sig1 = :(:%config);        # optional parameter
$sig2 = :(:$debug = False); # optional parameter, defaults to False
$sig3 = :(:$name!);         # mandatory 'name' named parameter

```

Default values can depend on previous parameters, and are (at least notionally) computed anew for each call

```raku
$sig1 = :($goal, $accuracy = $goal / 100);
$sig2 = :(:$excludes = ['.', '..']);        # a new Array for every call

```

## [Was an argument passed for a parameter?](#Signature_literals "go to top of document")[§](#Was_an_argument_passed_for_a_parameter? "direct link")

Table showing checks of whether an argument was passed for a given parameter:

| Parameter kind | Example | Comment | Check for no arg passed |
| --- | --- | --- | --- |
| Slurpy | \*@array | Don't check using .defined | if not @array |
| Required | $foo | Can't be omitted | (not applicable) |
| Optional | @bar = default | Pick a suitable default¹ | if @bar =:= default |

¹ A suitable default is an Object that has a distinct identity, as may be checked by the [`WHICH`](https://docs.raku.org/type/Mu#method_WHICH) method.

A parameter with a default is always *optional*, so there is no need to mark it with a `?` or the `is optional` trait.

Then you can use the `=:=` [container identity operator](https://docs.raku.org/language/operators#infix_=:=) in the body of the routine to check whether this exact default was bound to the parameter.

Example with a positional parameter:

```raku
my constant PositionalAt = Positional.new;

sub a (@list = PositionalAt) { say @list =:= PositionalAt }
a;              # OUTPUT: «True␤»
a [1, 2, 3];    # OUTPUT: «False␤»

```

Example with some scalar parameters:

```raku
my constant AnyAt = Any.new;

sub b ($x=AnyAt, :$y=AnyAt) { say $x =:= AnyAt; say $y =:= AnyAt }
b 1;            # OUTPUT: «False␤True␤»
b 1, :2y;       # OUTPUT: «False␤False␤»

```

If your parameters are typed, then the [type smileys](https://docs.raku.org/language/glossary#Type_smiley) can be used with [`multi`](https://docs.raku.org/language/functions#Multi-dispatch)s like this:

```raku
multi c (Int:U $z)  { say 'Undefined' }
multi c (Int:D $z)  { say 'Defined'   }
multi c (Int   $z?) { say 'Omitted'   }
c;              #Omitted
c (Int);        #Undefined
c 42;           #Defined

```

The examples use names like `PositionalAt` to reflect that the `.WHICH` test returns an object of type [`ObjAt`](/type/ObjAt), you are free to make up you own names.

# [Dynamic variables](#Signature_literals "go to top of document")[§](#Dynamic_variables "direct link")

[Dynamic variables](/language/variables#The_*_twigil) are allowed in signatures although they don't provide special behavior because argument binding does connect two scopes anyway.

# [Destructuring arguments](#Signature_literals "go to top of document")[§](#Destructuring_arguments "direct link")

Non-scalar parameters can be followed or substituted by a sub-signature in parentheses, which will destructure the argument given. The destructuring of a list is just its elements:

```raku
sub first(@array ($first, *@rest)) { $first }
```

or

```raku
sub first([$f, *@]) { $f }
```

While the destructuring of a hash is its pairs:

```raku
sub all-dimensions(% (:length(:$x), :width(:$y), :depth(:$z))) {
    $x andthen $y andthen $z andthen True
}
```

Pointy loops can also destructure hashes, allowing assignment to variables:

```raku
my %hhgttu = (:40life, :41universe, :42everything);
for %hhgttu -> (:$key, :$value) {
  say "$key → $value";
}
# OUTPUT: «universe → 41␤life → 40␤everything → 42␤»
```

In general, an object is destructured based on its attributes. A common idiom is to unpack a [`Pair`](/type/Pair)'s key and value in a for loop:

```raku
for <Peter Paul Merry>.pairs -> (:key($index), :value($guest)) { }
```

However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its [`Capture`](/routine/Capture) method.

# [Sub-signatures](#Signature_literals "go to top of document")[§](#Sub-signatures "direct link")

To match against a compound parameter use a sub-signature following the argument name in parentheses.

```raku
sub foo(|c(Int, Str)){
   put "called with {c.raku}"
};
foo(42, "answer");
# OUTPUT: «called with \(42, "answer")␤»
```

# [Long names](#Signature_literals "go to top of document")[§](#Long_names "direct link")

To exclude certain parameters from being considered in multiple dispatch, separate them with a double semicolon.

```raku
multi f(Int $i, Str $s;; :$b) { say "$i, $s, {$b.raku}" };
f(10, 'answer');
# OUTPUT: «10, answer, Any␤»
```

# [Capture parameters](#Signature_literals "go to top of document")[§](#Capture_parameters "direct link")

Prefixing a parameter with a vertical bar `|` makes the parameter a [`Capture`](/type/Capture), using up all the remaining positional and named arguments.

This is often used in `proto` definitions (like `proto foo (|) {*}`) to indicate that the routine's [`multi` definitions](/syntax/multi) can have any [type constraints](#Type_constraints). See [proto](/language/functions#proto) for an example.

If bound to a variable, arguments can be forwarded as a whole using the slip operator `|`.

```raku
sub a(Int $i, Str $s) { say $i.^name ~ ' ' ~ $s.^name }
sub b(|c) { say c.^name; a(|c) }
b(42, "answer");
# OUTPUT: «Capture␤Int Str␤»
```

# [Parameter traits and modifiers](#Signature_literals "go to top of document")[§](#Parameter_traits_and_modifiers "direct link")

By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter.

The `is copy` trait causes the argument to be copied, and allows it to be modified inside the routine

```raku
sub count-up($x is copy) {
    $x = ∞ if $x ~~ Whatever;
    .say for 1..$x;
}
```

The `is rw` trait, which stands for *is read-write*, makes the parameter bind to a variable (or other writable container). Assigning to the parameter changes the value of the variable at the caller side.

```raku
sub swap($x is rw, $y is rw) {
    ($x, $y) = ($y, $x);
}
```

On slurpy parameters, `is rw` is reserved for future use by language designers.

The [`is raw` trait](/type/Parameter#method_raw) is automatically applied to parameters declared with a [backslash](/language/variables#Sigilless_variables) or a [plus sign](#Single_argument_rule_slurpy) as a "sigil", and may also be used to make normally sigiled parameters behave like these do. In the special case of slurpies, which normally produce an [`Array`](/type/Array) full of [`Scalar`](/type/Scalar)s as described above, `is raw` will instead cause the parameter to produce a [`List`](/type/List). Each element of that list will be bound directly as raw parameter.

To explicitly ask for a read-only parameter use the `is readonly` trait. Please note that this applies only to the container. The object inside can very well have mutator methods and Raku will not enforce immutability on the attributes of the object.

Traits can be followed by the where clause:

```raku
sub ip-expand-ipv6($ip is copy where m:i/^<[a..f\d\:]>**3..39$/) { }
```


## dist_cpan-TYIL-Matrix-Bot.md
# NAME

Matrix::Bot

# AUTHOR

Patrick Spek [p.spek@tyil.work](mailto:p.spek@tyil.work)

# VERSION

0.2.0

# Description

A framework for writing Matrix bots

# Installation

Install this module through [zef](https://github.com/ugexe/zef):

```
zef install Matrix::Bot

```

# Usage

## Configuring the bot

First off, you have to instantiate the bot correctly. For this, a few arguments must be passed to `new`.

```
use Matrix::Bot;

my $bot = Matrix::Bot.new(
    home-server => "https://matrix.org",
    username => %*ENV<USER>,
    password => "",
    access-token => "",
    plugins => [],
);

$bot.run;

```

You must specify a password or access-token. If you supply both, the password will be ignored, and the access-token will be used directly. The list of plugins has to be filled with classes which implement `Matrix::Bot::Plugin`.

The `run` call starts the bots event loop. It will connect to Matrix, and start retrieving new messages on the channels it is joined in.

## Plugins

The simplest usage of the module would be using the `handle-room-text` method in a plugin. For instance, to repond to `"ping"` messages with a `"pong"`, you can write a plugin as follows.

```
use Matrix::Bot::Plugin;

class Local::Matrix::Plugin is Matrix::Bot::Plugin {
    multi method handle-room-text ($e where * eq "ping") {
	    "pong"
    }
}

```

## Logging

There is logging available in the module, through [`LogP6`](https://modules.perl6.org/dist/LogP6:cpan:ATROXAPER). This same logging object can be accessed by plugins, so they can log to the same stream when desired. To show all logging, you can set up a `filter`.

```
use LogP6 :configure;

filter(name => "", level => $trace, :update);

```

If you only want certain logging to be shown, you can set up one or more `cliche` calls instead. For instance, the following `cliche` shows only the messages on a channel.

```
cliche(
    name => "messages",
    matcher => "Matrix::Bot/message",
    grooves => (
	    writer(
		    pattern => "%msg",
		    handle => $*OUT,
		    filter(level => $info),
	    ),
    ),
);

```

More information on how to use `cliche`s, `filter`s and `LogP6` in general can be found in the `LogP6` documentation.

The following traits are used throughout `Matrix::Bot`:

* `Matrix::Bot`
* `Matrix::Bot/message`
* `Matrix::Bot/plugin($name)` (The `$name` corresponds to the name of the plugin's class)

# License

This module is distributed under the terms of the AGPL-3.0.


## dist_zef-kuerbis-Term-TablePrint.md
# NAME

Term::TablePrint - Print a table to the terminal and browse it interactively.

# SYNOPSIS

```
    use Term::TablePrint :print-table;

    my @table = ( [ 'id', 'name' ],
                  [    1, 'Ruth' ],
                  [    2, 'John' ],
                  [    3, 'Mark' ],
                  [    4, 'Nena' ], );

    # Functional style:

    print-table( @table );

    # or OO style:

    my $pt = Term::TablePrint.new();

    $pt.print-table( @table, :mouse(1) );

```

# DESCRIPTION

`print-table` shows a table and lets the user interactively browse it. It provides a cursor which highlights the row on which it is located. The user can scroll through the table with the different cursor keys.

## KEYS

Keys to move around:

* the ArrowDown key (or the j key) to move down and the ArrowUp key (or the k key) to move up.
* the PageUp key (or Ctrl-P) to go to the previous page, the PageDown key (or Ctrl-N) to go to the next page.
* the Insert key to go back 10 pages, the Delete key to go forward 10 pages.
* the Home key (or Ctrl-A) to jump to the first row of the table, the End key (or Ctrl-E) to jump to the last row of the table.

If *table-expand* is set to `0`, the Enter key closes the table if the cursor is on the first row.

If *table-expand* is enabled and the cursor is on the first row, pressing Enter three times in succession closes the table. If the cursor is auto-jumped to the first row, it is required only one Enter to close the table.

If the cursor is not on the first row:

* with the option *table-expand* disabled the cursor jumps to the table head if Enter is pressed.
* with the option *table-expand* enabled each column of the selected row is output in its own line preceded by the column name if Enter is pressed. Another Enter closes this output and goes back to the table output. If a row is selected twice in succession, the pointer jumps to the first row.

If the size of the window has changed, the screen is rewritten as soon as the user presses a key.

Ctrl-F opens a prompt. A regular expression is expected as input. This enables one to only display rows where at least one column matches the entered pattern. See option [search](#search).

## Output

If the option table-expand is enabled and a row is selected with Enter, each column of that row is output in its own line preceded by the column name.

If the table has more rows than the terminal, the table is divided up on as many pages as needed automatically. If the cursor reaches the end of a page, the next page is shown automatically until the last page is reached. Also if the cursor reaches the topmost line, the previous page is shown automatically if it is not already the first page.

For the output on the screen the table elements are modified. All the modifications are made on a copy of the original table data.

* If an element is not defined the value from the option *undef* is assigned to that element.
* Each character tabulation (`\t`) is replaces with a space.
* Vertical tabulations (`\v+`) are squashed to two spaces.
* Code points from the ranges of `control`, `surrogate` and `noncharacter` are removed.
* If the option *squash-spaces* is enabled leading and trailing spaces are removed and multiple consecutive spaces are squashed to a single space.
* If an element looks like a number it is right-justified, else it is left-justified.

If the terminal is too narrow to print the table, the columns are adjusted to the available width automatically.

* First, if the option *trunc-fract-first* is enabled and if there are numbers that have a fraction, the fraction is truncated up to two decimal places.
* Then columns wider than *min-col-width* are trimmed. See option [min-col-width](#min-col-width).
* If it is still required to lower the row width all columns are trimmed until they fit into the terminal.

# CONSTRUCTOR

The constructor method `new` can be called with named arguments. For the valid options see [OPTIONS](#OPTIONS). Setting the options in `new` overwrites the default values for the instance.

# ROUTINES

## print-table

`print-table` prints the table passed with the first argument.

```
print-table( @table, *%options );

```

The first argument is an list of arrays. The first array of these arrays holds the column names. The following arrays are the table rows where the elements are the field values.

The following arguments set the options (key-values pairs).

# OPTIONS

Defaults may change in future releases.

## prompt

String displayed above the table.

## color

If this option is enabled, SRG ANSI escape sequences can be used to color the screen output. Colors are reset to normal after each table cell.

0 - off (default)

1 - on (current selected element not colored)

2 - on (current selected element colored)

## decimal-separator

If set, numbers use *decimal-separator* as the decimal separator instead of the default decimal separator.

Allowed values: a character with a print width of `1`. If an invalid values is passed, *decimal-separator* falls back to the default value.

Default: . (dot)

## footer

If set (string), *footer* is added in the bottom line.

## max-rows

Set the maximum number of used table rows. The used table rows are kept in memory.

To disable the automatic limit set *max-rows* to `0`.

If the number of table rows is equal to or higher than *max-rows*, the last row of the output says `REACHED LIMIT "MAX_ROWS": $limit` or `=LIMIT= $limit` if the previous doesn't fit in the row.

Default: 50\_000

## max-width-exp

Set a maximum width of the expanded table row output. (See option [table-expand](#table-expand)).

## min-col-width

The columns with a width below or equal *min-col-width* are only trimmed if it is still required to lower the row width despite all columns wider than *min-col-width* have been trimmed to *min-col-width*.

Default: 30

## mouse

Set the *mouse* mode (see option `mouse` in [Term::Choose](https://github.com/kuerbis/Term-Choose-p6)).

Default: 0

## pad-row-edges

Add a space at the beginning and end of each row.

0 - off (default)

1 - enabled

## progress-bar

Set the progress bar threshold. If the number of fields (rows x columns) is higher than the threshold, a progress bar is shown while preparing the data for the output. Setting the value to `0` disables the progress bar.

Default: 5\_000

## save-screen

0 - off (default)

1 - use the alternate screen

## search

Set the behavior of Ctrl-F.

0 - off

1 - case-insensitive search (default)

2 - case-sensitive search

## squash-spaces

If *squash-spaces* is enabled, consecutive spaces are squashed to one space and leading and trailing spaces are removed.

Default: 0

## tab-width

Set the number of spaces between columns. If *format* is set to `2` and *tab-width* is even, the spaces between the columns are *tab-width* + 1 print columns.

Default: 2

## table-expand

If *table-expand* is enabled and Enter is pressed, the selected table row prints with each column on a new line. Pressing Enter again closes this view. The next Enter key press will automatically jump the cursor to the first row. If the cursor has automatically jumped to the first row, pressing Enter will close the table instead of expanding the first row. Pressing any key other than Enter resets these special behaviors.

```
    .----------------------------.        .----------------------------.
    |col1 | col2   | col3 | col3 |        |                            |
    |-----|--------|------|------|        |col1 : ..........           |
    |.... | ...... | .... | .... |        |                            |
    |.... | ...... | .... | .... |        |col2 : .....................|
   >|.... | ...... | .... | .... |        |       ..........           |
    |.... | ...... | .... | .... |        |                            |
    |.... | ...... | .... | .... |        |col3 : .......              |
    |.... | ...... | .... | .... |        |                            |
    |.... | ...... | .... | .... |        |col4 : .............        |
    |.... | ...... | .... | .... |        |                            |
    '----------------------------'        '----------------------------'

```

If *table-expand* is set to `0`, the cursor jumps to the to first row (if not already there) when Enter is pressed.

0 - off

1 - on (default)

## trunc-fract-first

If the terminal width is not wide enough and this option is enabled, the first step to reduce the width of the columns is to truncate the fraction part of numbers to 2 decimal places.

## undef

Set the string that will be shown on the screen instead of an undefined field.

Default: "" (empty string)

# ENVIRONMET VARIABLES

## multithreading

`Term::TablePrint` uses multithreading when preparing the list for the output; the number of threads to use can be set with the environment variable `TC_NUM_THREADS`.

# REQUIREMENTS

## Escape sequences

The control of the cursor location, the highlighting of the cursor position is done via escape sequences.

By default `Term::Choose` uses `tput` to get the appropriate escape sequences. If the environment variable `TC_ANSI_ESCAPES` is set to a true value, hardcoded ANSI escape sequences are used directly without calling `tput`.

The escape sequences to enable the *mouse* mode are always hardcoded.

If the environment variable `TERM` is not set to a true value, `vt100` is used instead as the terminal type for `tput`.

## Monospaced font

It is required a terminal that uses a monospaced font which supports the printed characters.

## Restrictions

Term::TablePrint is not installable on Windows.

# CREDITS

Thanks to the people from [Perl-Community.de](http://www.perl-community.de), from [stackoverflow](http://stackoverflow.com) and from #perl6 on irc.freenode.net for the help.

# AUTHOR

Matthäus Kiem [cuer2s@gmail.com](mailto:cuer2s@gmail.com)

# LICENSE AND COPYRIGHT

Copyright 2016-2025 Matthäus Kiem.

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.


## dist_github-alabamenhu-Intl-Number-Plural.md
# IntlNumberPlural

A number to determine the plural count category of a number for use in localization contexts

**Warning:** The name may change in the near-ish future (mid 2021) to be cohesive with other modules.
If it changes, I will continue to `provide` under the current name for at least one year.

To use:

```
use Intl::Number::Plural

                 # English  Arabic  Russian
plural-count 0;  # other    zero    many
plural-count 1;  # one      one     one
plural-count 2;  # other    two     few
plural-count 3;  # other    few     few
plural-count 6;  # other    few     many

```

There are six strings that can be returned by the function: **zero**, **one**, **two**, **few**, **many**, and **other**.
*Other* is the default and is used for all values in languages that do not have grammatical number.
Note that (as evidenced by the above table), the labels don't always correspond to what one might intuitively think.
Consequently, this is a module generally oriented towards makes of localization frameworks, and less so towards end-users.

The `plural-count` sub currently takes one or two positional arguments:

* **`number`** (required)
  The number whose count is to be determined.
* **`from`, `to`**
  The count is calculated for a range (`from .. to`).

There are two optional named parameters

* **`:language`**
  The language to be used in determining the count. Defaults to `user-language`.
* **`:type`**
  Acceptable values are **cardinal** and **ordinal**, defaults to *cardinal*. Some languages behave differently for these two types of numbers. Ignored for range calculations which always use *cardinal*

## Dependencies

* `Intl::CLDR`
  Houses the data for calculating the counts
* `Intl::UserLanguage`
  Determines the default language when not provided

## Todo

* Use `Intl::CLDR` enums once available.
* Add tests for major languages

## Version History

* **v0.5.4**
  * Fixed a small bug (*mod* → *%* for CLDR's *mod*)
* **v0.5.3**
  * Updated CLDR reference (was `.plurals` in beta, now is `.grammar.plurals`)
* **v0.5.2**
  * Added support for ranged
* **v0.5.1**
  * Initial release as separate module
* **v0.1** – **v0.5**
  * Included as a part of `Intl::CLDR`

## License and Copyright

© 2020-2021 Matthew Stephen Stuckwisch.
Licensed under the Artistic License 2.0.


## print.md
print

Combined from primary sources listed below.

# [In IO::Socket::Async](#___top "go to top of document")[§](#(IO::Socket::Async)_method_print "direct link")

See primary documentation
[in context](/type/IO/Socket/Async#method_print)
for **method print**.

```raku
method print(IO::Socket::Async:D: Str $str --> Promise)
```

Attempt to send `$str` on the `IO::Socket::Async` that will have been obtained indirectly via `connect` or `listen`, returning a [`Promise`](/type/Promise) that will be kept with the number of bytes sent or broken if there was an error sending.

# [In IO::Handle](#___top "go to top of document")[§](#(IO::Handle)_method_print "direct link")

See primary documentation
[in context](/type/IO/Handle#method_print)
for **method print**.

```raku
multi method print(**@text --> True)
multi method print(Junction:D --> True)
```

Writes the given `@text` to the handle, coercing any non-[`Str`](/type/Str) objects to [`Str`](/type/Str) by calling [`.Str`](/routine/Str) method on them. [`Junction`](/type/Junction) arguments [autothread](/language/glossary#Autothreading) and the order of printed strings is not guaranteed. See [write](/routine/write) to write bytes.

Attempting to call this method when the handle is [in binary mode](/type/IO/Handle#method_encoding) will result in [`X::IO::BinaryMode`](/type/X/IO/BinaryMode) exception being thrown.

```raku
my $fh = 'path/to/file'.IO.open: :w;
$fh.print: 'some text';
$fh.close;

```

# [In role IO::Socket](#___top "go to top of document")[§](#(role_IO::Socket)_method_print "direct link")

See primary documentation
[in context](/type/IO/Socket#method_print)
for **method print**.

```raku
method print(IO::Socket:D: Str(Cool) $string)
```

Writes the supplied string to the socket, thus sending it to other end of the connection. The binary version is [method write](#method_write).

Fails if the socket is not connected.

# [In Proc::Async](#___top "go to top of document")[§](#(Proc::Async)_method_print "direct link")

See primary documentation
[in context](/type/Proc/Async#method_print)
for **method print**.

```raku
method print(Proc::Async:D: Str() $str, :$scheduler = $*SCHEDULER)
```

Write the text data in `$str` to the standard input stream of the external program, encoding it as UTF-8.

Returns a [`Promise`](/type/Promise) that will be kept once the data has fully landed in the input buffer of the external program.

The `Proc::Async` object must be created for writing (with `Proc::Async.new(:w, $path, @args)`). Otherwise an [`X::Proc::Async::OpenForWriting`](/type/X/Proc/Async/OpenForWriting) exception will the thrown.

`start` must have been called before calling method print, otherwise an [`X::Proc::Async::MustBeStarted`](/type/X/Proc/Async/MustBeStarted) exception is thrown.

# [In Mu](#___top "go to top of document")[§](#(Mu)_method_print "direct link")

See primary documentation
[in context](/type/Mu#method_print)
for **method print**.

```raku
multi method print(--> Bool:D)
```

Prints value to `$*OUT` after stringification using `.Str` method without adding a newline at end.

```raku
"abc\n".print;          # OUTPUT: «abc␤»
```

# [In Independent routines](#___top "go to top of document")[§](#(Independent_routines)_sub_print "direct link")

See primary documentation
[in context](/type/independent-routines#sub_print)
for **sub print**.

```raku
multi print(**@args --> True)
multi print(Junction:D --> True)
```

Prints the given text on standard output (the [`$*OUT`](/language/variables#index-entry-%24%2AOUT) filehandle), coercing non-[`Str`](/type/Str) objects to [`Str`](/type/Str) by calling [`.Str` method](/routine/Str). [`Junction`](/type/Junction) arguments [autothread](/language/glossary#Autothreading) and the order of printed strings is not guaranteed.

```raku
print "Hi there!\n";       # OUTPUT: «Hi there!␤»
print "Hi there!";         # OUTPUT: «Hi there!»
print [1, 2, 3];           # OUTPUT: «1 2 3»
print "Hello" | "Goodbye"; # OUTPUT: «HelloGoodbye»
```

To print text and include the trailing newline, use [`put`](/type/independent-routines#sub_put).


## dist_github-scovit-NativeHelpers-CBuffer.md
[![Build Status](https://travis-ci.org/scovit/NativeHelpers-CBuffer.svg?branch=master)](https://travis-ci.org/scovit/NativeHelpers-CBuffer)

# NAME

NativeHelpers::CBuffer - A type for storing a caller allocated Buffer

# SYNOPSIS

```
    use NativeHelpers::CBuffer;

   class CBuffer is repr('CPointer') is export

```

The CBuffer object, is `repr("CPointer")`, as such, it can be directly used in
`NativeCall` signatures in the place of a Pointer.

# DESCRIPTION

NativeHelpers::CBuffer is a convinent way to store buffers and C NULL terminated strings

# EXAMPLE

```
    use NativeHelpers::CBuffer;

    my CBuffer $buf = CBuffer.new(100); # Allocates a buffer of 100 bytes

    sub strncpy(CBuffer, Str, size_t) is native { };
    strncpy($buf, "Uella!", 100);

    say $buf; # Uella!

```

# METHODS

## multi new (Int)

```
    multi method new(Int $size, :$with, :$of-type where { $of-type ∈ $types } = uint8)

```

Allocates a buffer of size `$size` elements, of type `$of-type` and with content a copy of `$with`.
Where `$with` can be either a Str or a Blob, and `$of-type` can be any of:

```
    my $types = (uint8, int8, uint16, int16, uint32, int32, uint64, int64, size_t, long, ulong, longlong, ulonglong);

```

## multi new (Blob)

```
    multi method new(Blob $init)

```

Allocates a buffer and store the content of the `$init` parameter.

## multi new (Str)

```
    multi method new(Str $init)

```

Allocates a buffer and store the content of the `$init` parameter as a NULL-terminated ASCII string.

## elems

```
    method elems(--> Int:D)

```

Return the number of elements stored

## bytes

```
    method bytes(--> Int:D)

```

Return the number of bytes stored

## type

```
    method type()

```

Return the type of the elements stored

## Blob

```
    method Blob(--> Blob:D)

```

Return a copy of the content as a Blob

## Pointer

```
    method Pointer(--> Pointer)

```

Return the pointer to the allocated buffer of type Pointer[self.type]

## Str

```
    method Str(--> Str:D)

```

Return a Str with the content decoded as null-terminated ASCII

## gist

same as `method Str`

## free

```
     method free()

```

Calls `free` the allocated buffer

# BUGS, TODOS and WARNINGS

At the moment, the `CBuffer` is immutable on the `perl` side,
once created and initialized, it's content can be modified only
by `C` functions. At the moment, the CBuffer is not resizable.

The `CBuffer` uses `NativeCall` to allocate memory, beware of not
using `CBuffer` in modules to allocate runtime memory during compilation.
In other words, do not use `CBuffer.new` in `BEGIN` blocks or `constant`
declarations, any abuse will result in Segmentation faults and/or
memory corruption!

In order to declare `C`-stile `#define` constants in modules,
use `perl` sub (or macro) instead:

```
   # the following, is equivalent to
     #define STRING_CONST     "The string"

   sub STRING_CONST is export { CBuffer.new("The string") };

```

# AUTHOR

Vittore F. Scolari [vittore.scolari@pasteur.fr](mailto:vittore.scolari@pasteur.fr)

# COPYRIGHT AND LICENSE

Copyright 2017 Institut Pasteur

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.