Creating operators
A short tutorial on how to declare operators and create new ones.
Operators are declared by using the sub
keyword followed by prefix
, infix
, postfix
, circumfix
, or postcircumfix
; then a colon and the operator name in a quote construct. For (post-)circumfix operators separate the two parts by white space.
sub hellosay .^name; # OUTPUT: «Sub»hello; # OUTPUT: «Hello, world!»my = sub (, ) ;say .^name; # OUTPUT: «Sub»say (2, 5); # OUTPUT: «7»# Alternatively we could create a more# general operator to sum n numberssub prefix:<Σ>( * )say Σ (13, 16, 1); # OUTPUT: «30»sub infix:<:=:>( is rw, is rw )my (, ) = ('A', 3);say ; # OUTPUT: «A»say ; # OUTPUT: «3»# Swap two variables' values:=: ;say ; # OUTPUT: «3»say ; # OUTPUT: «A»sub postfix:<!>( Int where * >= 0 )say 0!; # OUTPUT: «1»say 5!; # OUTPUT: «120»sub postfix:<♥>( )42♥; # OUTPUT: «I love 42!»sub postcircumfix:<⸨ ⸩>( Positional , Whatever )[1,2,3,4]⸨*⸩; # OUTPUT: «1…4»constant term:<♥> = "♥"; # We don't want to quote "love", do we?sub circumfix:<α ω>( );α♥ω; # OUTPUT: «♥ is the beginning and the end.»
These operators use the extended identifier syntax; that is what enables the use of any kind of codepoint to refer to them.