Title
[DRAFT] Synopsis 29 - Builtin Functions [DRAFT]
Version
Maintainer: Rod Adams <rod@rodadams.net>
Date: 12 Mar 2005
Last Modified: 16 Mar 2005
This document attempts to document the list of builtin functions in Perl 6. It assumes familiarity with Perl 5 and prior synopses.
Notes
In Perl 6, all builtin functions belong to a named package. Not all functions are guaranteed to be imported into the global package ::*
. In addition, the list of functions imported into ::*
will be subject to change with each release of Perl. Authors wishing to "Future Proof" their code should either specifically import the functions they will be using, or always refer to the functions by their full name.
After 6.0.0 comes out, global aliases will not be removed lightly, and will never be removed at all without having gone through a deprecation cycle of at least a year. In any event, you can specify that you want the interface for a particular version of Perl, and that can be emulated by later versions of Perl to the extent that security updates allow.
Where code is given here, it is intended to define semantics, not to dictate implementation.
Function Packages
Math::Basic
- abs
-
multi sub abs (: Num ?$x = $CALLER::_ ) returns Num
Absolute Value.
- exp
-
multi sub exp (: Num ?$exponent = $CALLER::_, Num +$base) returns Num
Performs similar to
$base ** $exponent
. $base defaults to the constant e. - log
-
multi sub log (: Num ?$x = $CALLER::_, Num +$base) returns Num
Logarithm of base $base, default Natural. Calling with
$x == 0
is an error. - log10
-
&log10<> := &log<>.assuming:base(10);
- rand
-
multi sub rand (: Num ?$x = 1, Num +$seed) returns Num
Random Number between 0 and 1, or rand()*$x. Optionally seed the generator with $seed.
- sign
-
multi sub sign (: Num ?$x = $CALLER::_) returns Int { if !defined($x) { return undef }; if $x < 0 { return -1 }; if $x > 0 { return 1 }; if $x == 0 { return 0 }; undef; }
- sqrt
-
multi sub sqrt (: Num ?$x = $CALLER::_) returns Num
$x ** 0.5
Math::Trig
- Standard Trig Functions
-
multi sub func (: Num ?$x = $CALLER::_, +$base) returns Num
where func is one of: sin, cos, tan, asin, acos, atan, sec, cosec, cotan, asec, acosec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, sech, cosech, cotanh, asech, acosech, acotanh.
Performs the various trigonmetric functions.
Option
$base
is used to declare your how you measure your angles. Given the value of an arc representing a single full revolution.$base Result ---- ------- /:i ^r/ Radians (2*pi) /:i ^d/ Degrees (360) /:i ^g/ Gradians (400) Num Units of 1 revolution.
- atan
-
multi sub atan (Num $x, Num $y : Num +$base) returns Num
This second form of
atan
computes the arctangent of $y/$x, and takes the quadrant into account. Otherwise behaves as other trigonometric functions. Replaces Perl 5atan2
. - pi
-
multi sub pi () returns Num
Perl6::Arrays
Note: These package names are pluralized to distinguish them from the classes that will likely assume the singular names.
- delete
-
multi method Perl6::Array::delete (: *@indices) returns List
Sets elements specified by
@indices
in the invocant to a non-existent state, as if they never had a value. Deleted elements at the end of an Array shorten the length of the Array, unless doing so would violate anis shape()
definition.@indices
is interpreted the same way as subscripting is in terms of slices and multidimensionality. See Synopsis 9 for details.Returns the value(s) previously held in deleted locations.
An unary form is expected. See Perl6::Hashes::delete
- exists
-
multi method Perl6::Array::exists (: Int *@indices) returns Bool
Returns True if the specified Array element has been assigned to. This is not the same as being defined.
Supplying a different number of indices than invocant has dimensions is an error.
An unary form is expected. See Perl6::Hashes::delete
- pop
-
multi sub pop () returns Scalar { pop @CALLER::_; } &pop<Array> := &splice<Array>.assuming(:offset(-1) :length(1));
Question: is
@CALLER::_
the right way to address the caller's slurpy array, per A06? - push
-
multi sub push (@array is rw : *@values) returns Int { splice(@array, @array.elems, 0, @values); @array.elems; }
- shift
-
multi sub shift () returns Scalar { shift @CALLER::_; } &shift<Array> := &splice<Array>.assuming(:offset(0) :length(1));
- splice
-
multi sub splice ( @array is rw : Int ?$offset = 0, Int ?$length, *@values) returns List is Lvalue
Behaves the similar as Perl 5
splice
.If
@array
is multidimensional,splice
operates only on the first dimension, and works with Array References. - unshift
-
multi sub unshift (@array is rw : *@values) returns Int { splice(@array, 0, 0, @values); @array.elems; }
- keys
- kv
- pairs
- values
-
multi sub keys (@array : Any|Junction *@indextests) returns Int|List multi sub kv (@array : Any|Junction *@indextests) returns Int|List multi sub pairs (@array : Any|Junction *@indextests) returns Int|(List of Pair) multi sub values (@array : Any|Junction *@indextests) returns Int|List
Iterates the elements of
@array
, in order.If
@indextests
are provided, only elements whose indices evaluate$index ~~ any(@indextests)
as true are iterated.What is returned at each element of the iteration varies with function.
values
returns the value of the associated element;kv
returns a 2 element list in (index, value) order,pairs
aPair(index, value)
.@array
is considered single dimensional. If it is in fact multi- dimensional, the values returned will be array references to the sub array.In Scalar context, they all return the count of elements that would have been iterated.
Perl6::Lists
- grep
-
multi sub grep (Any|Junction $test : *@values) returns List { gather { for @values -> $x { take $x if $x ~~ $test; } } }
- join
-
multi sub join (Str $delimiter : *@values) returns List { my $str = ~@values[0]; for 1..@values.end { $str ~= $delimiter ~ @values[$_]; } $str; } &join<> := &join<Str>.assuming:delimiter(' ');
- map
-
multi sub map (Code $expression : *@values) returns List { gather { while @values { take $expression .( splice(@values, 0, $expression.arity) ); } } }
- reduce
-
multi sub reduce (Code $expression : *@values) returns List { my $res; for @values -> $cur { FIRST {$res = $cur; next;} $res = &$expression($res, $cur); } $res; }
- reverse
-
multi sub reverse (%hash) returns Hash is default { my %result; for %hash.kv -> $k, $v { %result{$v} = $k; } %result; } multi sub reverse (: *@values) returns List|Str { given want { when List { gather { 1 while take pop @values; } } when Scalar { reverse @values ==> join; } } }
- sort
-
multi sub sort(Criterion @by : *@values) returns List multi sub sort(Criterion $by : *@values) returns List &sort<> := &sort<Criterion>.assuming(by => &infix:<cmp>); type KeyExtractor ::= Code(Any) returns Any; type Comparator ::= Code(Any, Any) returns Int; type Criterion ::= KeyExtractor | Comparator | Pair(KeyExtractor, Comparator);
Returns
@values
sorted, using criteria$by
or@by
for comparisions.@by
differs from$by
in that each criteria is applied, in order, until a non-zero (tie) result is achieved.Criterion can take a few different forms:
- Comparator
-
A closure with arity of 2, which returns negative/zero/positive, signaling the first arguement should be before/tied with/after the second in the final ordering of the List. aka "The Perl 5 way"
- KeyExtractor
-
A closure with arity of 1, which returns the "key" by which to sort. If the closure returns a Num,
<=>
is used for comparison, otherwisecmp
. - Pair(KeyExtractor, Comparator)
-
A combination of the two methods above, for when one wishs to take advantage of the internal caching of keys that is expected to happen, but wishes to compare them with something other than
<=>
orcmp
.
Any Criterion may recieve either or both of the traits
is descending
andin insensitive
to reverse the order of sort, or the adjust the case sensitivity ofcmp
as a Comparator.If all criteria are exhausted when comparing two elements, sort should return them in the same relative order they had in
@values
.See http://www.nntp.perl.org/group/perl.perl6.language/16578 for more details and examples.
- zip
-
multi sub zip (Array *@lists) returns List { gather { while any(@lists) { for @lists -> @list { take shift @list; } } } }
Example:
zip (1,4,7,10 ; 2,5,8,11 ; 3,6)
generates(1,2,3,4,5,6,7,8,undef,10,11,undef)
Perl6::Hashes
- delete
-
multi method Hash::delete (: *@keys) returns List multi method Hash::delete ( $key ) returns Scalar is default
Deletes the elements specified by
$key
or$keys
from the invocant. returns the value(s) that were associated to those keys.- Unary Form
-
Implementations should create a suitable macro, or otherwise support the unary form
delete %hash{$key}
in all it's forms. Below are some example translations. This list is not exhaustive.delete %hash{$key} %hash.delete{$key} delete %hash<key> %hash.delete{'key'} delete %hash<key1>{@keys} %hash<key1>.delete{@keys}
Since different implementations parse in different ways, no general macro will be provided at this time.
- exists
-
multi method Hash::exists ($key) returns Bool
True if invocant has an element whose key matches
$key
, false otherwise.An unary form is expected. See Perl6::Hashes::delete
- keys
- kv
- pairs
- values
-
multi sub keys (%hash : Any|Junction *@keytests) returns Int|List multi sub kv (%hash : Any|Junction *@keytests) returns Int|List multi sub pairs (%hash : Any|Junction *@keytests) returns Int|(List of Pair) multi sub values (%hash : Any|Junction *@keytests) returns Int|List
Iterates the elements of
%hash
in no apparent order, but the order will be the same between successive calls to these functions, as long as%hash
doesn't change.If
@keytests
are provided, only elements whose keys evaluate$key ~~ any(@keytests)
as true are iterated.What is returned at each element of the iteration varies with function.
keys
only returns the key;values
the value;kv
returns both as a 2 element list in (key, value) order,pairs
aPair(key, value)
.Note that
kv %hash
returns the same aszip(keys %hash; values %hash)
In Scalar context, they all return the count of elements that would have been iterated.
The lvalue form of
keys
is not longer supported. Use the.buckets
property instead.
TODO
- chomp
- chr
- hex
- index
- lc
- lcfirst
- length
- oct
- ord
- pack
- pos
- quotemeta
- rindex
- split
- sprintf
- study
- substr
- uc
- ucfirst
- unpack
- caller
- defined
- prototype
- ref
- die
- do
- eval
- exit
- sleep
- bless
- gmtime
- localtime
- time
- undef
- vec
- want
- caller
Obsolete
- chop
-
Use
chomp
orsubstr
- dbmopen, dbmclose
-
use DB_File;
- dump
-
With Parrot?
- each
-
while (defined(($key, $value) = each %hash)) { ... }
is now
for %hash.kv -> $key, $value { ... };
- format, formline, write
-
See Exgesis 7.
- reset
-
Was there a good use for this?
- scalar EXPR
-
Use the appropriate
/ \+ | ~ | \? | int /
operator. See S04Question: Is this correct?
- srand
-
rand(:seed($x))
Pending Apocalypse
The following functions are pending a future Apocalypse/Synopsis/p6l Discussion before progress can be made:
- A/S14: Tied Variables
-
tie tied untie
- A/S16: IPC / IO / Signals
-
-X accept alarm bind binmode chown close closedir connect eof fcntl fileno flock getc getpeername /[get|set][host|net|proto|serv|sock].*/ glob ioctl kill link listen lstat mkdir /msg.*/ open opendir pipe print printf read readdir readline readlink readpipe recv rename rewinddir rmdir seek seekdir select(both) /sem.*/ send setsockopt /shm.*/ shutdown socket socketpair stat symlink syscall sysopen sysread sysseek syswrite tell telldir truncate umask unlink utime warn
- A/S??: OS Interaction
-
chroot crypt exec getlogin /[get|set][pw|gr].*/ setpgrp setpriority system times
- A/S17: Threads and Multiprocessing
-
fork lock wait waitpid
Additions
Is your favorite function, which you spent weeks successfully arguing on perl6-language to get accepted, nowhere on this document? Have no fear. Email rod@rodadams.net with a brief description and a link to the thread on http://www.nntp.perl.org/group/perl.perl6.language, and it'll get listed.
Post errors to perl6-language.