11. Specific Datatype Modules
11.1. String
Module String
- Constant
__HAVE_SPRINTF_NEGATIVE_F__
constantintString.__HAVE_SPRINTF_NEGATIVE_F__- Description
Presence of this symbol indicates that
sprintf()supports little endian output for the 'F'-format specifier.- See also
sprintf(),lfun::_sprintf()
- Constant
__HAVE_SPRINTF_STAR_MAPPING__
constantintString.__HAVE_SPRINTF_STAR_MAPPING__- Description
Presence of this symbol indicates that
sprintf()supports mappings for the '*'-modifier syntax.- See also
sprintf(),lfun::_sprintf()
- Method
bits
int(0..)bits(stringdata)- Description
Gives the actual number of bits needed to represent every character in the string. Unlike
widththat only looks at the allocated string width,bitsactually looks at the maximum used character and delivers a more precise answer than just 8, 16, or 32 bits. The empty string results in 0.
- Method
capitalize
stringcapitalize(stringstr)- Description
Convert the first character in
strto upper case, and return the new string.- See also
lower_case(),upper_case()
- Method
common_prefix
stringcommon_prefix(array(string)strs)- Description
Find the longest common prefix from an array of strings.
- Method
count
intcount(stringhaystack,stringneedle)- Description
Count the number of non-overlapping times the string
needleoccurs in the stringhaystack. The special cases for the needle""is that it occurs one time in the empty string, zero times in a one character string and between every character (length-1) in any other string.- See also
search(),`/()
- Method
expand_tabs
stringexpand_tabs(strings,int(1..)|voidtab_width,string|voidtab,string|voidspace,string|voidnewline)- Description
Expands tabs in a string to ordinary spaces, according to common tabulation rules.
- Method
fuzzymatch
int(0..100)fuzzymatch(stringa,stringb)- Description
This function compares two strings using a fuzzy matching routine. The higher the resulting value, the better the strings match.
- See also
Array.diff(),Array.diff_compare_table()Array.diff_longest_sequence()
- Method
hex2string
string(8bit)hex2string(string(8bit)hex,int(0..2)|voidstrict_mode)- Description
Convert a string of hexadecimal digits to binary data.
- Parameter
hex String containing hexadecimal characters.
- Parameter
strict_mode Level of strictness. Defaults to
0:0Traditional mode: Non-hexadecimal characters will be ignored when between tuples. Eg.
"Z00 00"is ok, but"0 00Z0"isn't.1Lenient mode: Only Control characters and white-space will be ignored when between tuples. Eg.
"00 00"is ok, but"Z00 00"and"0 000"are not.2Strict mode: No non-hexadecimal characters are allowed.
- Note
The
strict_modeparameter was added in Pike 9.0.- See also
string2hex()
- Method
implode_nicely
stringimplode_nicely(array(string|int|float)foo,string|voidseparator)- Description
This function implodes a list of words to a readable string, e.g.
({"straw","berry","pie"})becomes"straw, berry and pie". If the separator is omitted, the default is"and". If the words are numbers they are converted to strings first.- See also
`*()
- Method
int2hex
stringint2hex(intx)- Description
Same as
sprintf("%x",x);, i.e. returns the integerxin hexadecimal base using lower cased symbols.- See also
sprintf()
- Method
int2roman
stringint2roman(intm)- Description
Converts the provided integer to a roman integer (i.e. a string).
- Throws
Throws an error if
mis outside the range 0 to 10000.
- Method
int2size
stringint2size(intsize)- Description
Returns the size as a memory size string with suffix, e.g. 43210 is converted into "42.2 kB". To be correct to the latest standards it should really read "42.2 KiB", but we have chosen to keep the old notation for a while. The function knows about the quantifiers kilo, mega, giga, tera, peta, exa, zetta and yotta.
- Method
levenshtein_distance
intlevenshtein_distance(stringa,stringb)- Description
This function calculates the Levenshtein distance between two strings a and b. The Levenshtein distance describes the minimal number of character additions, removals or substitutions to apply to convert a to b.
Mathematically, the Levenshtein distance between two strings a, b is given by lev_a,b(|a|,|b|) where
lev_a,b(i, j) == max(i, j), if min(i, j) == 0 lev_a,b(i, j) == min( lev_a,b(i, j-1)+1, lev_a,b(i-1, j)+1, lev_a,b(i-1, j-1) + a_i!=b_j ), else
Note that the first element in the minimum corresponds to inserting a character to a (or deleting a character from b), the second to deleting a character from a and the third to match or mismatch, depending on whether the respective characters are equal.
Example: For example, the Levenshtein distance between "pike" and "bikes" is 2, since the following two edits change one into the other, and there is no way to do it with fewer than two edits: - "pike" -> "bike" (substitute "p" with "b") - "bike" -> "bikes" (add "s" at the end)
Note that the cost to compute the Levenshtein distance is roughly proportional to the product of the two string lengths. So this function is usually used to aid in fuzzy string matching, when at least one of the strings is short.
- Method
normalize_space
stringnormalize_space(strings,string|voidwhitespace)- Parameter
s Is returned after white space in it has been normalised. White space is normalised by stripping leading and trailing white space and replacing sequences of white space characters with a single space.
- Parameter
whitespace Defines what is considered to be white space eligible for normalisation. It has a default value that starts with
" \t\r\n\v\f"and in addition to that contains all whitespace characters part of Unicode. The first character denotes the character for replacing whitespace sequences.- Note
Trailing and leading whitespace around \r and \n characters is stripped as well (only useful if they're not in the
whitespaceset).- Note
This function is a lot faster with just one argument (i.e. the builtin whitespace set has an optimised code path).
- Method
range
array(int) range(strings)- Description
Returns the character range of a string in an array of two elements. The first element contains the lower bound and the second the upper. The precision is only 8 bits, so for wide strings only character blocks are known.
- Method
secure
stringsecure(stringstr)- Description
Marks the string as secure, which will clear the memory area before freeing the string.
- See also
Object.secure()
- Method
sillycaps
stringsillycaps(stringstr)- Description
Convert the first character in each word (separated by spaces) in
strto upper case, and return the new string.
- Method
soundex
stringsoundex(stringword)- Description
Returns the soundex value of
wordaccording to the original Soundex algorithm, patented by Margaret O´Dell and Robert C. Russel in 1918. The method is based on the phonetic classification of sounds by how they are made. It was only intended for hashing of english surnames, and even at that it isn't that much of a help.
- Method
status
stringstatus(intverbose)- Description
Get string table statistics.
- Returns
Returns a string with an ASCII table containing the current string table statistics.
- Note
Currently returns the empty string (
"") ifverboseis zero.- Note
The formatting and contents of the result may vary between different versions of Pike.
- Method
string2hex
stringstring2hex(stringdata,void|int(0..)flags)- Description
Convert a string of binary data to a hexadecimal string.
- Parameter
flags The binary or of the following flags:
1Use upper case characters.
2The input is in little-endian byte order.
- See also
hex2string()
- Method
trim
stringtrim(strings)- Description
Trim leading and trailing white spaces characters (space, tab, newline, carriage return, form feed, vertical tab and all the white spaces defined in Unicode) from the string
s.
- Method
trim_whites
stringtrim_whites(strings)- Description
Trim leading and trailing spaces and tabs from the string
s.
- Method
width
int(8)|int(16)|int(32)width(strings)- Description
Returns the width of a string.
- Returns
Three return values are currently possible:
8The string
sonly contains characters <= 255.16The string
sonly contains characters <= 65535.32The string
scontains characters >= 65536.- Note
It is possible that a future version of Pike may return further values. In particular the width
7seems like it could be useful.
Class String.Bootstring
- Description
This class implements the "Bootstring" string transcoder described in ftp://ftp.rfc-editor.org/in-notes/rfc3492.txt.
- Method
create
String.BootstringString.Bootstring(intbase,inttmin,inttmax,intskew,intdamp,intinitial_bias,intinitial_n,intdelim,stringdigits)- Description
Creates a Bootstring transcoder instance using the specified parameters.
- Parameter
base The base used by the variable-length integers.
- Parameter
tmin The minimum threshold digit value for the variable-length integers. Must be >=0 and <= tmax.
- Parameter
tmax The maximum threshold digit value for the variable-length integers. Must be <= base-1.
- Parameter
skew The skew term for the bias adapation. Must be >= 1.
- Parameter
damp The damping factor for the bias adaption. Must be >= 2.
- Parameter
initial_bias The initial bias for the variable-length integer thresholding. initial_bias % base must be <= base - tmin.
- Parameter
initial_n The first code point outside the "basic" set of code points.
- Parameter
delim The "basic" code point used as the delimiter.
- Parameter
digits The "basic" code points used as digits. The length of the string should be the same as the base parameter.
- Method
decode
stringdecode(strings)- Description
Decodes a Bootstring encoded string of "basic" code points back to the original string space.
Class String.Buffer
- Description
A buffer, used for building strings. It's conceptually similar to a string, but you can only
addstrings to it, and you can onlygetthe value from it once.There is a reason for those seemingly rather odd limitations, it makes it possible to do some optimizations that really speed things up.
You do not need to use this class unless you add very many strings together, or very large strings.
- Example
For the fastest possible operation, write your code like this:
String.Buffer b =String.Buffer();function add = b->add; .. call add several times in code ... string result = b->get();// also clears the buffer
- Method
_search
int(0..)search(String.Bufferfrom,intcharacter,int|voidstart,int|voidend)- Description
Search for a
characterin the buffer, starting the scan fromstartand ending atend(inclusive).- Returns
Returns to position in the buffer where the character was found on success, and
UNDEFINEDon failure.- See also
Stdio.Buffer()->_search(),search(),lfun::_search()
- Method
_search
int(0..)search(String.Bufferfrom,stringsubstring,int|voidstart,int|voidend)- Description
Search for a
substringin the buffer, starting the scan fromstartand ending atend(inclusive).- Returns
Returns to position in the buffer where the substring was found on success, and
UNDEFINEDon failure.- See also
Stdio.Buffer()->_search(),search(),lfun::_search()
- Method
_sprintf
stringsprintf(stringformat, ... String.Bufferarg ... )- Description
It is possible to
sprintfa String.Buffer object as %s just as if it was a string.
- Method
add
intadd(string|String.Buffer...data)- Description
Adds
datato the buffer.- Returns
Returns the size of the buffer.
- Note
Pike 7.8 and earlier did not support adding
String.Buffers directly.
- Method
cast
(int)String.Buffer()
(float)String.Buffer()
(string)String.Buffer()
(array)String.Buffer()
(mapping)String.Buffer()
(multiset)String.Buffer()- Description
It is possible to cast a String.Buffer object to a
stringand anint.
- Method
clear
voidclear()- Description
Empty the buffer, and don't care about the old content.
- Note
This function was not available in Pike 7.8 and earlier.
- See also
get()
- Method
create
String.BufferString.Buffer(intinitial_size)- Description
Initializes a new buffer.
If no
initial_sizeis specified, 256 is used. If you know approximately how big the buffer will be, you can optimize the operation ofadd()(slightly) by passing the size to this function.
- Method
get
stringget()- Description
Get the data from the buffer.
- Note
This will clear the data in the buffer
- See also
get_copy(),clear()
- Method
get_copy
stringget_copy()- Description
Get the data from the buffer. Significantly slower than
get, but does not clear the buffer.- See also
get()
Class String.Iterator
- Description
An object of this class is returned by
get_iterator()when called with a string.- See also
get_iterator
Class String.Replace
- Description
This is a "compiled" version of the
replacefunction applied on a string, with more than one replace string. The replace strings are given to the create method as a from and to array and are then analyzed. The`()is then called with a string and the replace rules in the Replace object will be applied. The Replace object is used internally by the Pike optimizer and need not be used manually.
Class String.SingleReplace
- Description
This is a "compiled" version of the
replacefunction applied on a string, with just one replace string. The replace strings are given to the create method as a from and tom string and are then analyzed. The`()is then called with a string and the replace rule in the Replace object will be applied. The Replace object is used internally by the Pike optimizer and need not be used manually.
Class String.SplitIterator (< StringType >)
- Description
An iterator that iterates over substrings of a string, separated by a character or several different characters.
- Note
Typically you don't need to explicitly use the
SplitIterator. Expressions like the following are automatically optimized into using aSplitIterator.foreach(str/"\n",string line) write("%s\n", line);
- Method
create
String.SplitIteratorString.SplitIterator(StringTypebuffer,int|array(int)|multiset(int)split_set,int|voidflags,function(:StringType|zero)|voidfeed)- Parameter
buffer The string to split.
- Parameter
split_set The character or characters to split on.
- Parameter
flags Skip empty elements if set.
- Parameter
feed Callback function that is called once the
bufferis used up and the SplitIterator wants more data.
Module String.Elite
- Method
elite_string
stringelite_string(stringin,int(0..100)|voidleetp,bool|voideightbit)- Description
Translates a string to 1337. The optional argument leetp is the maximum percentage of leetness (100=max leet, 0=no leet).
The translation is performed in three steps, first the necessary elite translations (picture -> pic, cool->kewl etc), then optional translations (ok->k, dude->dood, -ers -> -orz), then calls elite_word on the resulting words.
- Method
elite_word
stringelite_word(stringin,int(0..100)|voidleetp,int(0..2)|voideightbit)- Description
Translates one word to 1337. The optional argument leetp is the maximum percentage of leetness (100=max leet, 0=no leet). elite_word only do character-based translation, for instance from "k" to "|<", but no language translation (no "cool" to "kewl").
- Method
elite_string
Module String.HTML
- Description
Functions that helps generating HTML. All functions generates HTML that is XHTML compliant as well as backwards compatible with old HTML standards in what extent is possible.
- Method
pad_rows
array(array(string)) pad_rows(array(array(string))rows,string|voidpadding)- Description
Pads out the rows in a array of rows to equal length. The new elements in the rows will have the value provided in
padding, or " ".
- Method
select
stringselect(stringname,array(string)|array(array(string))choices,void|stringselected)- Description
Creates an HTML select list.
- Parameter
name The name of the select list. Will be used in the name attribute of the select element.
- Parameter
choices May either be an array of strings, where each string is a choice, or an array of pairs. A pair is an array with two strings. The first string is the value of the choice while the second string is the presentation text associated with the value.
- Parameter
selected The value that should be selected by default, if any.
- Example
select("language", ({ ({ "eng", "English" }), ({ "swe", "Swedish" }), ({ "nor", "Norwegian" }) }), "swe");
- Method
simple_obox
stringsimple_obox(array(array(string))rows,void|stringframe_color,string|voidcell_color,void|stringwidth,void|stringpadding,void|function(int,int,string,string:string)cell_callback)- Description
This function should solve most of the obox needs that arises. It creates a table out of the array of arrays of strings fed into it. The tables will (with default settings) have a thin black outline around the table and between its cells. Much effort has gone into finding a simple HTML reresentation of such obox that is rendered in a similar way in all popular browsers. The current implementation has been tested against IE, Netscape, Mozilla, Opera and Konquest.
- Parameter
rows Simply an array of arrays with strings. The strings are the values that should appear in the table cells. All rows should have equal number of cells, otherwise the result will not be very eye pleasing.
- Parameter
frame_color The color of the surrounding frame. Defaults to "#000000".
- Parameter
cell_color The background color of the cells. Defaults to "#ffffff".
- Parameter
width The border width. Defaults to "1".
- Parameter
padding The amount of padding in each cell. Defaults to "3".
- Parameter
cell_callback If provided, the cell callback will be called for each cell. As in parameters it will get the current x and y coordinates in the table. The upper left cell is 0,0. In addition to the coordinates it will also receive the background color and the contents of the current cell. It is expected to return a td-element.
- Example
function cb = lambda(int x, int y, string bgcolor, string contents) { if(y%2) return "<td bgcolor='#aaaaff'>"+contents+"</td>"; return "<td bgcolor='"+bgcolor+"'>"+contents+"</td>"; } simple_obox(my_rows, "#0000a0", 0, "1", "3", cb);
- See also
pad_rows
Class String.HTML.OBox
- Description
Provides the same functionality as the
simple_oboxfunction, in a "streaming" way. The real gain is different addtition methods as well as the possibility to change the cell callback at any time.- See also
simple_obox
- Method
add_raw_cell
voidadd_raw_cell(stringcell)- Description
Adds this cell to the table unmodified, e.g. it should have an enclosing td or th element.
- Method
add_row
voidadd_row(array(string)cells)- Description
Adds a complete row. If the current row is nonempty a new row will be started.
- Method
add_tagdata_cell
voidadd_tagdata_cell(stringtag,mapping(string:string)args,stringcontents)- Description
Creates a cell from the provided arguments and adds it to the table.
- Parameter
tag The name of the element that should be produces. Typically "td" or "th".
- Parameter
args A mapping with the elements attributes.
- Parameter
contents The element contents.
- Method
cast
(int)String.HTML.OBox()
(float)String.HTML.OBox()
(string)String.HTML.OBox()
(array)String.HTML.OBox()
(mapping)String.HTML.OBox()
(multiset)String.HTML.OBox()- Description
It is possible to case this object to a string, which does the same as calling
render, and to an array, which returns the cells in an array of rows.
- Method
create
String.HTML.OBoxString.HTML.OBox(void|stringframe_color,void|stringcell_color,void|stringwidth,void|stringpadding,void|function(int,int,string,string:string)cell_callback)
- Method
new_row
voidnew_row()- Description
Begin a new row. Succeeding cells will be added to this row instead of the current.
- Method
set_cell_callback
voidset_cell_callback(function(int,int,string,string:string)cell_callback)
- Method
set_extra_args
voidset_extra_args(array(mapping(string:string))extra_args)- Description
The argument in the mappings will be added to the cell in the cooresponding column of the table.
- Constant
__HAVE_SPRINTF_NEGATIVE_F__
11.2. Array
Module Array
- Description
General functions to operate on arrays.
- Method
all
boolall(arraya,function(int(0),mixed... :mixed)predicate,mixed...extra_args)- Description
Returns 1 if all of the elements in
afulfills the requirementpredicate(a[i], @extra_args), otherwise 0. The predicate should return non-zero for an element that meets the requirements and zero for those that do not.- Example
Array.all( ({ 2, 4, 6, 8 }), `<, 17 )
- See also
any,has_value
- Method
any
boolany(arraya,function(__unknown__,__unknown__... :mixed)predicate,mixed...extra_args)- Description
Returns 1 if any of the elements in
afulfills the requirementpredicate(a[i], @extra_args), otherwise 0. The predicate should return non-zero for an element that meets the requirements and zero for those that do not.- Example
Array.any( ({ 2, 4, 6, 8 }), `>, 5 )
- See also
all,has_value
- Method
arrayify
arrayarrayify(void|array|mixedx)- Description
Make an array of the argument, if it isn't already. An undefined argument gives the empty array. This is useful when something is either an array or a basic datatype, for instance in headers from the MIME module or Protocols.HTTP.Server.
- Parameter
x Result depends of the argument type:
- arrayp(x)
arrayify(x) => x
- undefinedp(x)
arrayify(x) => ({})
- otherwise
arrayify(x) => ({ x })
- Method
columns
array(array) columns(arrayx,arrayind)- Description
Get multiple columns from an array.
This function is equivalent to
map(ind, lambda(mixed i) { return column(x, i); })- See also
column()
- Method
combinations
array(array) combinations(arrayarr,int(0..)len)- Description
Returns an array of all combinations of length
lenof elements fromarr.- See also
permute()
- Method
common_prefix
arraycommon_prefix(array(array)arrs)- Description
Find the longest common prefix from an array of arrays.
- See also
String.common_prefix
- Method
compact_diff3
array(array(array)) compact_diff3(arraya,arrayb,arrayold)- Description
Given three arrays like those returned from
diff3, this function "compacts" the diff3 result by removing all differences where a and b agrees against old. The result is on the same form as the result fromdiff, and doesn't include the sequence from old.
- Method
count
intcount(array|mapping|multisethaystack,mixedneedle)mapping(mixed:int) count(array|mapping|multisethaystack)- Description
Returns the number of occurrences of
needleinhaystack. If the optionalneedleargument is omitted,countinstead works similar to the unix command sort|uniq -c, returning a mapping with the number of occurrences of each element inhaystack. For array or mappinghaystacks, it's the values that are counted, for multisets the indices, as you'd expect.- See also
String.count,search,has_value
- Method
diff
array(array(array)) diff(arraya,arrayb)- Description
Calculates which parts of the arrays that are common to both, and which parts that are not.
- Returns
Returns an array with two elements, the first is an array of parts in array
a, and the second is an array of parts in arrayb.- See also
diff_compare_table(),diff_longest_sequence(),String.fuzzymatch()
- Method
diff3
array(array(array)) diff3(arraya,arrayb,arrayc)- Description
Return the three-way difference between the arrays.
- See also
Array.diff(),Array.diff_longest_sequence()
- Method
diff_compare_table
array(array(int)) diff_compare_table(arraya,arrayb)- Description
Returns an array which maps from index in
ato corresponding indices inb.> Array.diff_compare_table( ({ "a","b","c" }), ({ "b", "b", "c", "d", "b" })); Result: ({ ({ }), ({ 0, 1, 4 }), ({ 2 }) })- See also
diff(),diff_longest_sequence(),String.fuzzymatch()
- Method
diff_dyn_longest_sequence
array(int) diff_dyn_longest_sequence(arraya,arrayb)- Description
Gives the longest sequence of indices in
bthat have corresponding values in the same order ina.This function performs the same operation as
diff_longest_sequence(), but uses a different algorithm, which in some rare cases might be faster (usually it's slower though).- See also
diff_longest_sequence(),diff(),diff_compare_table(),String.fuzzymatch()
- Method
diff_longest_sequence
array(int) diff_longest_sequence(arraya,arrayb)- Description
Gives the longest sequence of indices in
bthat have corresponding values in the same order ina.- See also
diff(),diff_compare_table(),String.fuzzymatch()
- Method
dwim_sort_func
int(-1..1)dwim_sort_func(stringa,stringb)- Description
Sort strings containing numbers with respect to their values rather than according to their formatting (this most notably causes leading zeroes to be ignored/unnecessary).
- Example
"foo7" will be sorted before "foo27", which will be before "foo100".
- Method
everynth
array(mixed) everynth(array(mixed)a,void|int(1..)n,void|int(0..)start)- Description
Return an array with every
n:th element of the arraya.If
nis zero every other element will be returned.- See also
splice(),`/()
- Method
flatten
arrayflatten(arraya,mapping(array:array)|voidstate)- Description
Flatten a multi-dimensional array to a one-dimensional array.
- Note
Prior to Pike 7.5.7 it was not safe to call this function with cyclic data-structures.
- Method
greedy_diff
array(array(array)) greedy_diff(arrayfrom,arrayto)- Description
Like
Array.diff, but tries to generate bigger continuous chunks of the differences, instead of maximizing the number of difference chunks. More specifically,greedy_diffoptimizes the cases whereArray.diffreturns({ ..., A, Z, B, ({}), C, ... })({ ..., A, X, B, Y+B, C, ... })into the somewhat shorter diff arrays({ ..., A, Z, B+C, ... })({ ..., A, X+B+Y, B+C, ... })
- Method
interleave_array
array(int) interleave_array(array(mapping(int:mixed))tab)- Description
Interleave a sparse matrix.
Returns an array with offsets that describe how to shift the rows of
tabso that only at most one non-zero value exists in every column.
- Method
longest_ordered_sequence
array(int) longest_ordered_sequence(arraya)- Description
Find the longest ordered sequence of elements.
This function returns an array of the indices in the longest ordered sequence of elements in the array.
- See also
diff()
- Method
lyskom_sort_func
int(-1..1)lyskom_sort_func(stringa,stringb)- Description
Sort comparison function that does not care about case, nor about the contents of any parts of the string enclosed with '()'
Example: "Foo (bar)" is given the same weight as "foo (really!)"
- Method
oid_sort_func
int(-1..1)oid_sort_func(stringa,stringb)- Description
Sort with care of numerical sort for OID values, e.g. "1.2.1" before "1.11.1".
- Returns
-1a<b0a==b1a>b- Note
In Pike 7.6 and older this function returned
0both whena<banda==b.- See also
sort_array
- Method
partition
array(array) partition(arraya,function(int(0),mixed... :mixed)arbiter,mixed...extra_args)- Description
Splits an array in two, according to an arbitration function
arbiter. The elements inawho return non-zero for the expressionarbiter(a[i], @extra_args) end up in the first sub-array, the others in the second. The order is preserved from the original array.- Example
Array.partition( enumerate( 9 ), lambda(int n) { return n>3 && n<7; } ); > ({ ({ 4, 5, 6 }), ({ 0, 1, 2, 3, 7, 8 }) })
- See also
filter,`/,`%
- Method
permute
arraypermute(arrayin,int(0..)number)- Description
Give a specified permutation of an array.
The number of permutations is equal to
sizeof((the factorial of the size of the given array).in)!- See also
shuffle()
- Method
pop
arraypop(arraylist)- Description
Pops and returns the last value of the array, shortening the array by one element. If there are no elements in the array then 0 is returned otherwise an array is returned where the first returned element is the popped value, and the second element is the modified array.
- Example
Array.pop(({ "a", "b", "c", "d" })); > ({ "d", ({ "a", "b", "c" }) })
- See also
ADT.Stack,ADT.Stack.pop,ADT.Stack.quick_pop
- Method
push
arraypush(arraylist,mixedelement)- Description
Threats an Array as a stack and pushes the element onto the end.
- Example
Array.push(({ "a", "b", "c", "d" }), "e"); > ({ "a", "b", "c", "d", "e" })
- See also
ADT.Stack,ADT.Stack.push
- Method
reduce
mixedreduce(function(:void)fun,arrayarr,mixed|voidzero)- Description
reduce()sends the first two elements inarrtofun, then the result and the next element inarrtofunand so on. Then it returns the result. The function will returnzeroifarris the empty array. Ifarrhas only one element, that element will be returned.- See also
rreduce()
- Method
rreduce
mixedrreduce(function(:void)fun,arrayarr,mixed|voidzero)- Description
rreduce()sends the last two elements inarrtofun, then the third last element inarrand the result tofunand so on. Then it returns the result. The function will returnzeroifarris the empty array. Ifarrhas only one element, that element will be returned.- See also
reduce()
- Method
search_array
intsearch_array(arrayarr,string|function(:void)|intfun,mixed...args)- Description
search_array()works likemap(), only it returns the index of the first call that returnes true instead.If no call returns true, -1 is returned.
- See also
sum(),map()
- Method
shift
array|zeroshift(arraylist)- Description
Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array it returns 0. Returns an array where the first element is the shifted value and the second element is the modified array.
- Example
Array.shift(({ "a", "b", "c", "d"})); > ({ "a", ({ "b", "c", "d" }) })
- See also
ADT.Stack
- Method
shuffle
arrayshuffle(arrayarr)- Description
shuffle()gives back the same elements, but in random order. The array is modified destructively.- See also
permute()
- Method
sort_array
arraysort_array(arrayarr,function(:void)|voidcmp,mixed...args)- Description
This function sorts the array
arrafter a compare-functioncmpwhich takes two arguments and should return1if the first argument is larger then the second. Returns the sorted array -arris not sorted destructively.The remaining arguments
argswill be sent as 3rd, 4th etc. argument tocmp.If
cmpis omitted,`>()is used instead.- See also
map(),sort(),`>(),dwim_sort_func,lyskom_sort_func,oid_sort_func
- Method
splice
array(mixed) splice(array(mixed)arr1,array(mixed)arr2,array(mixed) ...more_arrays)- Description
Splice two or more arrays.
This means that the returned array has the first element in the first given array, then the first argument in next array and so on for all arrays. Then the second elements are added, etc.
- See also
`/(),`*(),`+(),`-(),everynth()
- Method
sum
mixedsum(arraya)- Description
Sum the elements of an array using `+. The empty array results in 0.
- Method
sum_arrays
arraysum_arrays(function(int(0)... :mixed)sum,array...args)- Description
Applies the function
sumcolumnwise on the elements in the provided arrays. E.g.sum_arrays(`+,a,b,c)does the same as`+(a[*],b[*],c[*]).
- Method
transpose
array(array) transpose(array(array)matrix)- Description
Takes an array of equally sized arrays (essentially a matrix of size M*N) and returns the transposed (N*M) version of it, where rows and columns are exchanged for one another.
- Method
uniq
arrayuniq(arraya,function(mixed,mixed:bool)|voidcmp)- Description
Remove elements that are duplicates.
- Parameter
a Array that may contain duplicate elements.
- Parameter
cmp Function to use for comparing elements. If not specified, the elements will be compared with
`==()and hashed (cflfun::__hash()).- Returns
This function returns an copy of the array
awith all duplicate values removed. The order of the values is kept in the result; it's always the first of several equal elements that is kept.- Note
The
cmpargument is only available in Pike 9.1 and later.- Note
The
cmpfunction MUST return non-zero for all element pairs thatpredef::`==()considers equal.
- Method
uniq2
arrayuniq2(arraya)- Description
Perform the same action as the Unix uniq command on an array, that is, fold consecutive occurrences of the same element into a single element of the result array:
aabbbcaababb -> abcabab.
See also the
uniqfunction.
- Method
unshift
arrayunshift(arraylist,mixedelement)- Description
Does the opposite of "shift". Or the opposite of a "push", depending on how you look at it. Prepends the element to the front of the array and returns the new array.
- Example
Array.unshift(({ "b", "c", "d" }), "a"); > ({ "a", "b", "c", "d" })
- See also
ADT.Stack
11.3. Mapping
Module Mapping
Class Mapping.Iterator
- Description
An object of this class is returned by
get_iterator()when called with a mapping.- See also
get_iterator
Class Mapping.ShadowedMapping
- Description
A mapping look-alike that overrides (ie shadows) another
parentmapping.The class implements most of the usual mapping operations.
- Method
create
Mapping.ShadowedMappingMapping.ShadowedMapping(mapping|ShadowedMappingparent,mapping|ShadowedMappingparent,mapping|voidshadow,int(0..2)|voidmodify_parent)- Parameter
parent Mapping to be shadowed.
- Parameter
shadow Initial shadow of
parent.- Parameter
modify_parent Modifications should be done to
parentrather than toshadow.0Modifications should be done only to
shadow.1Entries that already present in
shadowcan be modified by later operations. Other modifications will be performed inparent.2All modifications will be performed in
parent. If the entry to be modified is present inshadow, it will be removed from it.
11.4. Multiset
Module Multiset
- Description
Multiset handling.
11.5. Int
Module Int
- Constant
NATIVE_MIN
Constant NATIVE_MAX constantInt.NATIVE_MINconstantInt.NATIVE_MAX- Description
The limits for using the native representation of integers on the current architecture. Any integer that is outside this range uses a more complex and slower representation. Also, some builtin functions that don't expect very large integers might start to complain about invalid argument type when given values outside this range (they typically say something like "Expected integer, got object").
NATIVE_MINis not greater than-2147483648(-0x80000000).NATIVE_MAXis not less than2147483647(0x7fffffff).- Note
The size of the native integers can be controlled when Pike is compiled with the configure flags
--with-int-int,--with-long-int, and--with-long-long-int. The default is to use the longest available integer type that fits inside a pointer, which typically means that it's 64 bit on "true" 64 bit architectures.
- Method
parity
boolparity(int(0..)value)- Description
Returns the parity of the integer
value. If the parity is odd 1 is returned. If it is even 0 is returned.
- Method
reflect
int(0..)reflect(intvalue,int(0..)bits)- Description
Reverses the order of the low order
bitsnumber of bits of the valuevalue.- Note
Any higher order bits of the value will be cleared. The returned value will thus be unsigned.
- See also
reverse(),swap_word(),swap_long()
- Method
swap_long
int(32bit)swap_long(int(32bit)i)- Description
Swaps the upper and lower word in a longword, and the upper and lower bytes in the words. Simply put, the bytes are reversed.
- See also
swap_word()
- Method
swap_word
int(16bit)swap_word(int(16bit)i)- Description
Swaps the upper and lower byte in a word.
- See also
swap_long()
Class Int.Inf
- Description
The type of
Int.inf. Do not create more instances of this.
- Constant
NATIVE_MIN
11.6. Float
Module Float
- Constant
DIGITS_10
Constant MIN_10_EXP
Constant MAX_10_EXP
Constant MIN
Constant MAX
Constant EPSILON constantFloat.DIGITS_10constantFloat.MIN_10_EXPconstantFloat.MAX_10_EXPconstantFloat.MINconstantFloat.MAXconstantFloat.EPSILON- Description
These constants define the limits for floats on the current architecture:
- DIGITS_10
The number of decimal digits that can be represented. Any number with this many decimal digits can be stored in a float and converted back to decimal form without change.
DIGITS_10is not less than6.- MIN_10_EXP
- MAX_10_EXP
Limits of the exponent in decimal base. 10 raised to any number within this range can be represented in normalized form.
MIN_10_EXPis not greater than-37.MAX_10_EXPis not less than37.- MIN
The smallest normalized float greater than zero. It's not greater than
1e-37.- MAX
The largest finite float. It's not less than
1e37.- EPSILON
The difference between 1 and the smallest value greater than 1 that can be represented. It's not greater than
1e-5.
- Note
The size of the float type can be controlled when Pike is compiled with the configure flags
--with-double-precisionand--with-long-double-precision. The default is to use the longest available float type that fits inside a pointer.
- Constant
FLOAT_PRECISION
Constant DOUBLE_PRECISION
Constant LONG_DOUBLE_PRECISION constantFloat.FLOAT_PRECISIONconstantFloat.DOUBLE_PRECISIONconstantFloat.LONG_DOUBLE_PRECISION- Description
Tells which C compiler float type that is used for Pike floats. Only one of these constants will exist (with the value
1) at runtime.- FLOAT_PRECISION
The
floattype of the C compiler is used.- DOUBLE_PRECISION
The
doubletype of the C compiler is used.- LONG_DOUBLE_PRECISION
The
long doubletype of the C compiler is used.
- Note
The float type can be controlled when Pike is compiled with the configure flags
--with-double-precisionand--with-long-double-precision. The default is to use the longest available float type that fits inside a pointer.
- Constant
DIGITS_10
11.7. Function
Module Function
- Method
Y
function(:void) Y(function(:void)f)- Description
The dreaded fixpoint combinator "Y".
The Y combinator is useful when writing recursive lambdas. It converts a lambda that expects a self-reference as its first argument into one which can be called without this argument.
- Example
This example creates a lambda that computes the faculty function.
Function.Y(lambda(function f,int n){return n>1? n*f(n-1): 1;})- See also
this_function
- Method
call_callback
voidcall_callback(function(:void)f,mixed...args)- Description
Call a callback function, but send throws from the callback function (ie, errors) to master()->handle_error. Also accepts if f is zero (0) without error.
- Example
Functions.call_callback(the_callback,some,arguments);equals
{mixed err=catch{if(the_callback) the_callback(some,arguments);};if(err) master()->handle_error(err);}(Approximately, since call_callback also calls handle_error if 0 were thrown.)
- Method
composite
function(:void) composite(function(:void) ...f)- Description
Creates a composite function of the provided functions. The composition function of f() and g(), q(x)=f(g(x)), is created by
function q = Function.composite(f, g);.- Example
map(input/",",Function.composite(String.trim, upper_case));
- Method
curry
function(mixed... :function(mixed... :mixed|void)) curry(function(:void)f)- Description
Partially evaluate a function call.
This function allows N parameters to be given to a function taking M parameters (N<=M), yielding a new function taking M-N parameters.
What is actually returned from this function is a function taking N parameters, and returning a function taking M-N parameters.
- Example
This example creates a function adding 7 to its argument.
Function.curry(`+)(7)
- Method
defined
stringdefined(function(:void)fun)- Description
Returns a string with filename and linenumber where
funwas defined.Returns
0(zero) when no line can be found, e.g. for builtin functions and functions in destructed objects.
- Method
splice_call
mixedsplice_call(arrayargs,function(:void)f,mixed|void...extra)- Description
Calls the given function with the
argsarray plus the optional extra arguments as its arguments and returns the result.Most useful in conjunction with
map, and particularly in combination withsscanfwith"...%{...%}..."scan strings (which indeed was what it was invented for in the first place).- Parameter
args The first arguments the function
fexpects.- Parameter
f The function to apply the arguments on.
- Parameter
extra Optional extra arguments to send to
f.- Returns
Whatever the supplied function
freturns.- Example
class Product(string name,string version){string _sprintf(){return sprintf("Product(%s/%s)", name, version);}} map(({({"pike","7.1.11"}),({"whitefish","0.1"})}),Function.splice_call, Product);({/* 2 elements */ Product(pike/7.1.11), Product(whitefish/0.1)})
- Method
uncurry
function(mixed... :mixed) uncurry(function(:void)f)- Description
This function, given a function taking N parameters, returns a new function taking N+1 parameters. The first argument will be ignored.
- Example
> Function.uncurry(`+)(7,2,3) Result: 5
Class Function.Iterator (< ValueType >)
- Description
An object of this class is returned by
get_iterator()when called with a function.- See also
get_iterator()
- Method
_iterator_next
protectedValueType_iterator_next()- Description
Call the wrapped function and return its result.
Class Function.bind
- Description
Partially evaluate a function call.
This function returns a function that when called will do the specified argument mapping. It is similar to
curry, but allows more dynamic changes of the argument evaluation, you can leave the first argument unspecified while setting others, or simply change the argument order.- Parameter
f The first argument is the function to be called.
- Parameter
bind_args All other arguments are either a generic value, which will be sent as-is to the function or one of the placeholder values defined in
Function.Placeholder, or one of your own implementation (inheritFunction.Placeholder.Baseand implement the value function.).- Example
This example returns a function that limits the given argument to between 0 and 99.
importFunction.Placeholder;function clip =Function.bind(limit, 0, arg0, 100);
Module Function.Placeholder
- Description
Placeholder arguments for
Function.bind
- Constant
arg0
Constant arg1
Constant arg2
Constant arg3
Constant arg4
Constant arg5
Constant arg6
Constant arg7
Constant arg8
Constant arg9 constantFunction.Placeholder.arg0constantFunction.Placeholder.arg1constantFunction.Placeholder.arg2constantFunction.Placeholder.arg3constantFunction.Placeholder.arg4constantFunction.Placeholder.arg5constantFunction.Placeholder.arg6constantFunction.Placeholder.arg7constantFunction.Placeholder.arg8constantFunction.Placeholder.arg9- Description
arg<n> will return an instance of
Argthat returns the n:th arg. For convenience for c++11 developers _0, _1 etc also works.Note that arg0 is the first argument, not arg1
- Variable
rest
ArgFunction.Placeholder.rest- Description
Return all arguments not used by any
ArgorSplice.Unlike
Splicethis will return non-continous unused arguments.- Example
This creates a version of call_out that has the function argument as the last argument
import Function.Placeholder; Function.bind( call_out, Arg(-1), rest)
Class Function.Placeholder.Arg
- Description
Arg(x) returns the value of argument X
Class Function.Placeholder.Expr
- Description
Expr(x) returns the result of calling
x. The function will be passed the list of arguments.If _splice is true, zero or more argument is returned in an array
Function.Placeholder.arg1 is thus more or less equivalent to
Expr(lambda(array args){return args[1];});
- Variable
func
Variable _splice function(:void) Function.Placeholder.Expr.funcvoid|boolFunction.Placeholder.Expr._splice
- Method
Y
11.8. Program
Module Program
- Method
all_inherits
array(program) all_inherits(programp)- Description
Enumerate all programs this program inherits, directly or indirectly. Similar to inherit_tree() but returns a flat array.
- Example
> class a{} > class b{} > class c{ inherit a; } > class d{ inherit b; inherit c; } > Program.inherit_tree(d); Result: ({ /* 3 elements */ b, c, a })
- Method
annotations
multiset(Pike.Annotation) annotations(programx,bool|voidno_recurse)- Description
Return a multiset with the annotations for all symbols in
xattached to this program.- Parameter
x Program whose identifiers should be returned.
- Parameter
no_recurse Do not include annotations recursively added via inherits.
- Returns
Returns an multiset with annotations added directly to this program.
- Note
This function was added in Pike 8.1.
- See also
indices(),values(),types(),lfun::_annotations(),::_annotations()
- Method
defined
stringdefined(programp)- Description
Returns a string with filename and linenumber describing where the program
pwas defined.The returned string is of the format
"filename:linenumber".If it cannot be determined where the program was defined,
0(zero) will be returned.
- Method
defined
string|zerodefined(programx,stringidentifier)- Description
Returns a string with filename and linenumber where
identifierinxwas defined.Returns
0(zero) when no line can be found, e.g. for builtin functions.If
identifiercan not be found inxthis function returns where the program is defined.
- Method
inherit_list
array(program) inherit_list(programp)- Description
Returns an array with the programs that
phas inherited.
- Method
inherit_tree
arrayinherit_tree(programp)- Description
Recursively builds a inheritance tree by fetching programs inheritance lists.
- Returns
Returns an array with programs or arrays as elements.
- Example
> class a{} > class b{} > class c{ inherit a; } > class d{ inherit b; inherit c; } > Program.inherit_tree(d); Result: ({ /* 3 elements */ d, ({ /* 1 element */ program }), ({ /* 2 elements */ c, ({ /* 1 element */ program }) }) })
- Method
all_inherits
11.9. ADT
Module ADT
- Description
Various Abstract Data Types.
- Constant
__HAVE_CIRCULAR_LIST_REPLACE_BACK__
constantintADT.__HAVE_CIRCULAR_LIST_REPLACE_BACK__- Description
Presence of this symbol indicates that
CircularList()->replace_back()is implemented.
- Constant
__HAVE_CIRCULAR_LIST_REPLACE_FRONT__
constantintADT.__HAVE_CIRCULAR_LIST_REPLACE_FRONT__- Description
Presence of this symbol indicates that
CircularList()->replace_front()is implemented.
Class ADT.BitBuffer
- Description
Implements a FIFO bit buffer, i.e. a buffer that operates on bits instead of bytes. It is not designed for performance, but as a way to handle complicated file formats and other standards where you may need to work on unaligned data units of sub byte size, without having to fry your brain while keeping track of all the bits yourself.
- Example
> ADT.BitBuffer b=ADT.BitBuffer(); > b->put1(2); (1) Result: ADT.BitBuffer(11) > b->put0(15); (2) Result: ADT.BitBuffer("\300\0"0) > b->drain(); (3) Result: "\300\0" > sizeof(b); (4) Result: 1
- Method
_sizeof
intsizeof(ADT.BitBufferarg)- Description
sizeof()will return the number of bits in the buffer.
- Method
create
ADT.BitBufferADT.BitBuffer(void|string(8bit)data)- Description
The buffer can be initialized with initial data during creation.
- Method
get
intget(intbits)- Description
Get
bitsfrom the buffer.- Throws
Throws an error in case of data underflow.
- Note
The bits are extracted with the most significant bit first.
- Method
put
this_programput(intvalue,intbits)- Description
Put
bitsnumber of bits with the valuevalueinto the buffer.- Note
valuemust not be larger than what can be stored with the number of bits given inbits.- Note
The bits are added to the buffer with the most significant bit first.
Class ADT.CircularList (< ValueType >)
- Description
This is an circular list implemented by an array. It has a constant time complexity for pop and push. It has a limited max size but it can be increased with the methods
allocate()or [set_max_size()].
- Method
_equal
boolequal(ADT.CircularListfrom,mixedcoll)- Returns
Returns true if the object
collis aCircularListand contains the same values in the same order.
- Method
_get_iterator
ADT.CircularLista;
foreach( a; index; value ) orCircularListIterator(<ValueType>) _get_iterator(void|intind)- Description
Create and initiate a new CircularListIterator that could be used to iterate over this list.
- Parameter
ind If an
indvalue is supplied the iterator will be positioned at that index.- Returns
An iterator.
- Method
_indices
array(ValueType) indices(ADT.CircularListarg)- Returns
The indices in this list as an array.
- Method
_insert_element
void_insert_element(intindex,ValueTypevalue)- Description
Insert an element in the list at the position
index, the value at the positionindexand all above will have their index increased by one.- Parameter
index The index to insert the value at.
- Parameter
value The new value.
- Throws
An error if the index is out of range.
- Note
The
max_sizeis increased by one.- See also
_remove_element()
- Method
_remove_element
ValueType_remove_element(intindex)- Description
Remove the values at index
indexfrom the list.- Parameter
index The index to remove.
- Returns
The removed value.
- Throws
An error if the index is out of range.
- Note
The
max_sizeis decreased by one.- See also
_insert_element()
- Method
_search
int(-1..)search(ADT.CircularListfrom,ValueTypevalue,void|int(0..)start)- Description
Search the list for a specific value. Return the index of the first value that is equal to
value. If no value was foundUNDEFINEDis returned instead- Parameter
value The value to find
- Parameter
start If a start value is supplied it will start searching at the index
start.- Returns
Returns the index of the found value or
-1.- Throws
An error if the start is out of range.
- Method
_values
array(ValueType) values(ADT.CircularListarg)- Returns
The values in this list as an array.
- Method
`+
CircularList(<ValueType>) res =ADT.CircularList()+coll- Description
Addition operator
Append the content of this CircularList and @
colland return the results as a newCircularList.- Parameter
coll The lists to append to this list
- Returns
The result of the append as a new
CircularList.
- Method
`[]
ValueTyperes =ADT.CircularList()[index]- Description
Index operator
- Parameter
index The index to get the value for, may be negative to index from the end.
- Returns
The value at the index
index- Throws
An error if the index is out of range.
- Method
`[]=
ADT.CircularList()[index] =value- Description
Index assign operator. Set the value at the index
indexto bevalue- Parameter
index The index to set
- Parameter
value The new value
- Returns
The new value at the index
index- Throws
An error if the index is out of range.
- Method
add
voidadd(ValueTypevalue,bool|voidforce)- Description
Add a value at the front of the list
- Parameter
value The value to add.
- Parameter
force Add the value even if the list is full, in which case the element at the back of the list will be removed.
- Throws
An error if the list is full and
forceis false.- Note
forcewas not supported in Pike 8.0.1800 and earlier.- Note
This is the same operation as
push_front().- See also
replace_back(),replace_front(),push_back(),push_front()
- Method
allocate
voidallocate(int(0..)elements)- Description
Increase the maxsize of the CircularlList.
- Parameter
elements Add this number of new elements to the list.
- See also
set_max_size()
- Method
cast
(array(ValueType))ADT.CircularList()- Description
Cast operator.
- Parameter
type Casts to this type.
Casts to the following types are supported:
"array"Cast the content of this list to an array.
- Returns
An array with the contents of this list.
- Method
create
ADT.CircularListADT.CircularList(array(ValueType)|intarg)- Description
Creates a new
CircularListaround the array arg or a newCircularListwith the maximum size of arg.
- Method
delete_value
int(-1..)delete_value(ValueTypevalue)- Description
Remove the first occurrence of the value
valuefrom the list.- Parameter
value The value to remove from the list.
- Returns
The index of the removed element or -1 if there was no value to remove.
- Method
first
__deprecated__CircularListIterator(<ValueType>) first()- Description
Create and initiate a new CircularListIterator that could be used to iterate over this list.
- Returns
An iterator positioned before the first element of the list.
- Deprecated
Replaced by
_get_iterator.With the Pike 8.1 and later iterator API this is identical to
last()and_get_iterator().- See also
_get_iterator(),last()
- Method
last
__deprecated__CircularListIteratorlast()- Description
Create and initiate a new CircularListIterator that could be used to iterate over this list.
- Returns
An iterator positioned after the last element of the list.
- Deprecated
Replaced by
_get_iterator.With the Pike 8.1 and later iterator API this is identical to
first()and_get_iterator().- See also
_get_iterator(),first()
- Method
max_size
int(0..)max_size()- Returns
Returns the maximal size of this list.
- See also
set_max_size()
- Method
peek_back
ValueTypepeek_back()- Returns
The value at the back of the list but do not remove it from the list.
- Method
peek_front
ValueTypepeek_front()- Returns
The value at the front of the list but do not remove it from the list.
- Method
pop_back
ValueTypepop_back()- Description
Remove the value at the back of the list and return it.
- Returns
The value at the back of the list.
- Method
pop_front
ValueTypepop_front()- Description
Remove the value at the front of the list and return it.
- Returns
The value at the front of the list.
- Method
push_back
voidpush_back(ValueTypevalue,bool|voidforce)- Description
Add a new value at the end of the list.
- Parameter
value The value to add.
- Parameter
force Add the value even if the list is full, in which case the element at the front of the list will be removed.
- Throws
An error if the list is full and
forceis false.- Note
forcewas not supported in Pike 8.0.1800 and earlier.- See also
add(),push_front()
- Method
push_front
voidpush_front(ValueTypevalue,bool|voidforce)- Description
Add a new value at the front of the list.
- Parameter
value The value to add.
- Parameter
force Add the value even if the list is full, in which case the element at the back of the list will be removed.
- Throws
An error if the list is full and
forceis false.- Note
forcewas not supported in Pike 8.0.1800 and earlier.- Note
This is the same operation as
add().- See also
add(),push_back()
- Method
replace_back
ValueType|zeroreplace_back(ValueTypevalue)- Description
Replace a value to the back of the list.
- Parameter
value The value to add.
- Returns
Returns the element that was at the front of the list if it was full, and
UNDEFINEDotherwise.This operation is similar to:
mixed replace_back(mixed value){mixed ret =UNDEFINED;if(sizeof(this) == max_size()){ ret = pop_front();} push_back(value);return ret;}- Note
Presence of this function is indicated by
__HAVE_CIRCULAR_LIST_REPLACE_BACK__.- See also
add(),pop_back(),push_front(),replace_front()
- Method
replace_front
ValueType|zeroreplace_front(ValueTypevalue)- Description
Replace a value to the front of the list.
- Parameter
value The value to add.
- Returns
Returns the element that was at the back of the list if it was full, and
UNDEFINEDotherwise.This operation is similar to:
mixed replace_front(mixed value){mixed ret =UNDEFINED;if(sizeof(this) == max_size()){ ret = pop_back();} push_front(value);return ret;}- Note
Presence of this function is indicated by
__HAVE_CIRCULAR_LIST_REPLACE_FRONT__.- See also
add(),pop_back(),push_front(),replace_back()
- Method
set_max_size
int(0..)set_max_size(int(0..)new_size)- Parameter
new_size The new size of the list.
- Returns
Returns the old maximal size of the list.
- Note
When reducing in size, elements that no longer fit are dropped from the back.
- See also
allocate(),max_size()
Class ADT.CircularList.CircularListIterator (< ValueType >)
- Description
This is the iterator for the CircularList. It implements the IndexIterator and the OutputIterator.
- Method
_equal
boolequal(ADT.CircularList.CircularListIteratorfrom,mixediter)- Description
Compare this iterator with another iterator.
- Parameter
iter The iterator to compare with
- Returns
Returns true if both iterators iterates over the same objects and are positioned at the same spot.
- Method
_iterator_next
bool_iterator_next()- Description
Advances the iterator to the next position.
- Returns
Returns
1if the iterator advanced to an existing node, andUNDEFINEDotherwise.
- Method
`+
CircularListIterator(<ValueType>) res =ADT.CircularList.CircularListIterator()+steps- Description
Move the iterator
stepssteps forward (negative value onstepswill cause the iterator to move backwards) and return the result as a new iterator.- Returns
A new iterator positioned
stepssteps forward.
- Method
`+=
ADT.CircularList.CircularListIterator()+=steps- Description
Move this iterator
stepssteps forward (negative value onstepswill cause the iterator to move backwards) and return the result.- Returns
This iterator positioned
stepssteps forward.
- Method
`-
CircularListIterator(<ValueType>) res =ADT.CircularList.CircularListIterator()-steps- Description
Move the iterator
stepssteps backwards (negative value onstepswill cause the iterator to move forwards) and return the result as a new iterator.- Returns
A new iterator positioned
stepssteps backwards.
- Method
`<
boolres =ADT.CircularList.CircularListIterator()<iter- Description
Less then operator
- Returns
Returns true if this iterator has a lower index then
iter.
- Method
`>
boolres =ADT.CircularList.CircularListIterator()>iter- Description
Greater then operator
- Returns
Returns true if this iterator has a higher index then
iter.
- Method
create
ADT.CircularList.CircularListIteratorADT.CircularList.CircularListIterator(CircularList(<ValueType>)list,void|intstart)- Description
Creates a new iterator for the CircularList
list. Ifstartis supplied it will try to position the iterator atstart.
- Method
distance
intdistance(CircularListIterator(<ValueType>)iter)- Parameter
iter The iterator to measure the distance to.
- Returns
Returns distance between this iterator and
iter.- Throws
An error if the two iterator could not be compared.
- Note
This operation is only valid if both iterators are for the same
CircularListobject.
- Method
get_collection
CircularList(<ValueType>) get_collection()- Returns
Returns the CircularList this iterator currently iterates over.
- Method
has_next
boolhas_next(void|intsteps)- Returns
Returns true if it is possible to move
stepssteps forwards, ifstepsweren't supplied it check if it is possible to move one step forward.
- Method
has_previous
boolhas_previous(void|intsteps)- Returns
Returns true if it is possible to move
stepssteps backwards, ifstepsweren't supplied it check if it is possible to move one step backward.
Class ADT.Heap (< ValueType >)
- Description
This class implements a (min-)heap. The value of a child node will always be greater than or equal to the value of its parent node. Thus, the top node of the heap will always hold the smallest value.
- Method
adjust
Element(<ValueType>) adjust(ValueType|Element(<ValueType>)value)- Description
Takes a value in the heap and sorts it through the heap to maintain its sort criteria (increasing order).
- Parameter
value Either the element handle returned by
push(), or the pushed value itself.- Returns
Returns the element handle for the value (if present in the heap), and
0(zero) otherwise.
- Method
low_peek
Element(<ValueType>) low_peek()- Description
Returns the
Elementon top of the heap (which is also the one with the smallest value in the heap) without removing it.- Returns
Returns the smallest
Elementon the heap if any, andUNDEFINEDotherwise.- See also
peek(),low_pop(),pop()
- Method
low_pop
Element(<ValueType>) low_pop()- Description
Removes and returns the
Elementon top of the heap, which also is the smallest value in the heap.- Returns
Returns
UNDEFINEDif the heap is empty.- See also
pop(),peek(),push(),remove()
- Method
peek
ValueTypepeek()- Description
Returns the item on top of the heap (which is also the smallest value in the heap) without removing it.
- Returns
Returns the smallest value on the heap if any, and
UNDEFINEDotherwise.- See also
low_peek(),pop()
- Method
pop
ValueTypepop()- Description
Removes and returns the item on top of the heap, which also is the smallest value in the heap.
- Throws
Throws an error if the heap is empty.
- See also
low_pop(),peek(),push(),remove()
- Method
push
Element(<ValueType>) push(ValueType|Element(<ValueType>)value)- Description
Push an element onto the heap. The heap will automatically sort itself so that the smallest value will be at the top.
- Returns
Returns an element handle, which can be used with
adjust()andremove().- Note
If
valueis aHeap.Elementand already present on the heap this is equivalent to callingadjust().- See also
pop(),remove()
Class ADT.History (< ValueType >)
- Description
A history is a stack where you can only push entries. When the stack has reached a certain size the oldest entries are removed on every push. Other proposed names for this data type is leaking stack and table (where you push objects onto the table in one end and objects are falling off the table in the other.
- Generic
ValueType
__generic__mixedValueType=mixed- Description
Type for the individual elements on the history stack.
- Method
_indices
array(int) indices(ADT.Historyarg)- Description
Returns the index numbers of the history entries available.
- Method
_sizeof
intsizeof(ADT.Historyarg)- Description
A
sizeofoperation on this object returns the number of elements currently in the history, e.g. <= the current max size.
- Method
_values
array(ValueType) values(ADT.Historyarg)- Description
Returns the values of the available history entries.
- Method
`[]
ValueTyperes =ADT.History()[i]- Description
Get a value from the history as if it was an array, e.g. both positive and negative numbers may be used. The positive numbers are however offset with 1, so [1] is the first entry in the history and [-1] is the last.
- Method
`[]=
ADT.History()[i] =value- Description
Overwrite one value in the history. The history position may be identified either by positive or negative offset, like
`[].
- Method
create
ADT.HistoryADT.History(int(0..)max_size)- Description
max_sizeis the maximum number of entries that can reside in the history at the same time.
- Method
flush
voidflush()- Description
Empties the history. All entries in the history are removed, to allow garbage collect to remove them. The entry sequence counter is not reset.
- Method
get_first_entry_num
intget_first_entry_num()- Description
Returns the absolute sequence number of the oldest result still in the history. Returns 0 if there are no results in the history.
- Method
get_latest_entry_num
intget_latest_entry_num()- Description
Returns the absolute sequence number of the latest result inserted into the history.
- Method
get_maxsize
intget_maxsize()- Description
Returns the maximum number of values in the history
- See also
set_maxsize
- Method
query_no_adjacent_duplicates
boolquery_no_adjacent_duplicates()- Description
Tells if the History object allows adjacent equal values. 1 means that only uniqe values are allowed adter each other.
- See also
set_no_adjacent_duplicates
- Method
set_maxsize
voidset_maxsize(int_maxsize)- Description
Set the maximume number of entries that can be stored in the history simultaneous.
- See also
get_maxsize
Class ADT.Interval (< RangeType >)
- Method
create
ADT.IntervalADT.Interval(RangeType|Boundary(<RangeType>)a,RangeType|Boundary(<RangeType>)b)
Class ADT.Interval.Boundary (< RangeType >)
Class ADT.Interval.Closed (< RangeType >)
Class ADT.Interval.Open (< RangeType >)
- Method
create
Class ADT.List (< ValueType >)
- Description
Linked list of values.
- Method
_get_iterator
ADT.Lista;
foreach( a; index; value ) orprotectedIterator(<ValueType>) _get_iterator()
- Method
_sprintf
stringsprintf(stringformat, ... ADT.Listarg ... )- Description
Describe the list.
- See also
sprintf(),lfun::_sprintf()
- Method
_values
array(ValueType) values(ADT.Listarg)- Description
Returns an array of elements in the list.
- Method
append
voidappend(ValueType...values)- Description
Append
valuesto the end of the list.- See also
insert()
- Method
create
ADT.ListADT.List(ValueType...values)- Description
Create a new
List, and initialize it withvalues.
- Method
head
ValueTypehead()- Description
Get the element at the head of the list.
- Throws
Throws an error if the list is empty.
- See also
is_empty(),tail(),pop()
- Method
insert
voidinsert(ValueType...values)- Description
Insert
valuesat the front of the list.- See also
append()
- Method
is_empty
boolis_empty()- Description
Check if the list is empty.
- Returns
Returns
1if the list is empty, and0(zero) if there are elements in the list.
- Method
pop
ValueTypepop()- Description
Pop the element at the head of the list from the list.
- Throws
Throws an error if the list is empty.
- See also
is_empty(),head(),tail(),pop_back()
- Method
pop_back
ValueTypepop_back()- Description
Pop the element at the tail of the list from the list.
- Throws
Throws an error if the list is empty.
- See also
is_empty(),head(),tail(),pop()
- Method
tail
ValueTypetail()- Description
Get the element at the tail of the list.
- Throws
Throws an error if the list is empty.
- See also
is_empty(),head(),pop_back()
Class ADT.List.Iterator (< ValueType >)
- Description
predef::Iteratorthat loops over theList.
- Method
_iterator_next
protectedbool_iterator_next()- Description
Advance to the next element in the list.
- Returns
Returns
1on success, andUNDEFINEDat the end of the list.- See also
_iterator_prev()
- Method
_iterator_prev
ValueType|zero_iterator_prev()- Description
Retrace to the previous element in the list.
- Returns
Returns the new element on success, and
UNDEFINEDat the start of the list.- See also
_iterator_next()
- Method
_iterator_value
protectedValueType_iterator_value()- Returns
Returns the value at the current position.
- Method
`+=
ADT.List.Iterator()+=steps- Description
Advance or retrace the specified number of
steps.- See also
next(),prev
- Method
append
voidappend(ValueTypeval)- Description
Append
valafter the current position.- See also
insert(),delete(),set()
- Method
copy_iterator
Iterator(<ValueType>) copy_iterator()- Returns
Returns a copy of the iterator at its current position.
- Method
delete
voiddelete()- Description
Delete the current node.
The current position will advance to the next node. This function thus performes the reverse operation of
insert().- See also
insert(),append(),set()
- Method
first
boolfirst()- Description
Reset the iterator to point to the first element in the list.
- Returns
Returns
1if there are elements in the list, and0(zero) if the list is empty.
- Method
insert
voidinsert(ValueTypeval)- Description
Insert
valat the current position.- See also
append(),delete(),set()
- Method
next
boolnext()- Description
Advance to the next element in the list.
- Returns
Returns
1on success, and0(zero) at the end of the list.- See also
prev()
- Method
prev
boolprev()- Description
Retrace to the previous element in the list.
- Returns
Returns
1on success, and0(zero) at the beginning of the list.- See also
next()
- Method
set
voidset(ValueTypeval)- Description
Set the value of the current position to
val.- See also
insert(),append(),delete()
Class ADT.LowLevelStack (< ValueType >)
- Description
This class implements a simple stack. Instead of adding and removing elements to an array, and thus making it vary in size for every push and pop operation, this stack tries to keep the stack size constant. If however the stack risks to overflow, it will allocate double its current size, i.e. pushing an element on an full 32 slot stack will result in a 64 slot stack with 33 elements.
- See also
ADT.Stack
- Method
_search
int(-1..)search(ADT.LowLevelStackfrom,ValueTypeitem)- Description
Return the stack-depth to
item.This function makes it possible to use eg
search()andhas_value()on the stack.
- Method
_sizeof
int(0..)sizeof(ADT.LowLevelStackarg)- Description
sizeofon a stack returns the number of entries in the stack.
- Method
_values
array(ValueType) values(ADT.LowLevelStackarg)- Description
valueson a stack returns all the entries in the stack, in order.
- Method
`+
this_programres =ADT.LowLevelStack()+s- Description
A stack added with another stack yields a new stack with all the elements from both stacks, and the elements from the second stack at the top of the new stack.
- Method
create
ADT.LowLevelStackADT.LowLevelStack(int(0..)|voidinitial_size)- Description
An initial stack size can be given when a stack is cloned. The default value is
32.
- Method
pop
ValueTypepop(void|zeroval)array(ValueType) pop(int(1..)val)- Description
Pops and returns the top
valentries from the stack. If no value is given orvalis0, the top element is popped and returned. All popped entries are freed from the stack.- Note
If the stack is empty an error will be thrown.
- See also
quick_pop(),pop_to(),ADT.Stack
- Method
pop_to
voidpop_to(int(0..)depth)- Description
Pops entries from the stack until it reaches the specified depth.
The popped entries are not returned.
- Throws
Throws an error if there are fewer than
depthelements on the stack.- See also
pop(),quick_pop()
- Method
quick_pop
voidquick_pop(void|int(0..)val)- Description
Pops
valentries from the stack, or one entry if no value or0(zero) is given. The popped entries are not returned.- See also
pop(),pop_to()
- Method
reset
voidreset(int(0..)|voidinitial_size)- Description
Empties the stack, resets the stack pointer and shrinks the stack size to the given value or
32if none or0(zero) is given.- See also
create
- Method
set_stack
voidset_stack(array(ValueType)stack)- Description
Sets the stacks content to the provided array.
Class ADT.OrderedMapping (< IndexType, ValueType >)
- Description
This class works pretty much as a mapping except the order of the indices is kept in the order they are added. This class works equivalent to the Map() class in Javascript.
- Example
OrderedMapping m1 = OrderedMapping("foo", 1,"bar", 2); m1->gazonk = 3;foreach(m1;string key;int val){ write("# %s: %d\n", key, val);}/* output: # foo: 1 # bar: 2 # gazonk: 3 */ m_delete(m1,"gazonk"); m1 += OrderedMapping("afoo", 3);foreach(m1;string key;int val){ write("# %s: %d\n", key, val);}/* output: # foo: 1 # bar: 2 # afoo: 3 */
- Method
cast
(mapping)ADT.OrderedMapping()
(array)ADT.OrderedMapping()- Description
Cast the object into various other types.
- Note
This method can not be called on the object. A proper
(cast)has to be done.- Parameter
how mappingWill return a
mapping. This will of course break the "orderness" of this object's indices.arrayWill return an
array(array)where the inner array has two values where the first is the index and the second the value.multisetWill return the indices as a
multisetprogramWill return the
programthe object was instantiated from.
- Method
create
ADT.OrderedMappingADT.OrderedMapping(IndexType|ValueType...args)- Example
ADT.OrderedMapping m1 =ADT.OrderedMapping("key1","val1","key2","val2");- Throws
An error is thrown if the number of arguments isn't even.
- Parameter
args Odd arguments are the indices, even arguments the values.
"index", "value", "index", "value", ...
Class ADT.Priority_queue (< ValueType >)
- Description
This class implements a priority queue. Each element in the priority queue is assigned a priority value, and the priority queue always remains sorted in increasing order of the priority values. The top of the priority queue always holds the element with the smallest priority. The priority queue is realized as a (min-)heap.
- Generic
ValueType
__generic__mixedValueType=mixed- Description
Type for the individual elements in the queue.
- Method
adjust_pri
voidadjust_pri(elemhandle,int|floatnew_pri)- Description
Adjust the priority value
new_priof an elementhandlein the priority queue. The priority queue will automatically sort itself so that the element with the smallest priority value will be at the top.
- Method
peek
ValueTypepeek()- Description
Returns the item on top of the priority queue (which is also the element with the smallest priority value) without removing it.
- Method
pop
ValueTypepop()- Description
Removes and returns the item on top of the heap, which also is the smallest value in the heap.
Class ADT.Queue (< ValueType >)
- Description
A simple FIFO queue.
- Generic
ValueType
__generic__mixedValueType=mixed- Description
Type for the individual elements in the queue.
- Method
create
ADT.QueueADT.Queue(ValueType...args)- Description
Creates a queue with the initial items
argsin it.
- Method
get
ValueTypeget()- Description
Returns the next element from the queue, or
UNDEFINEDif the queue is empty.- See also
peek(),put()
- Method
peek
ValueType|zeropeek()- Description
Returns the next element from the queue without removing it from the queue. Returns
UNDEFINEDif the queue is empty.- Note
Prior to Pike 9.0 this function returned a plain
0when the queue was empty.- See also
get(),put()
Class ADT.Scheduler (< ValueType >)
- Description
This class implements a quantized resource scheduler.
Weighted consumers are added to the scheduler with
add(), which returns aConsumerobject.When there's some of the resource available to be consumed the resource owner calls
get(), which returns theConsumerthat is to use the resource.Consumer()->consume()is then called with the fraction of the quanta that was consumed (typically1.0). The amount of resources allocated to a consumer is proportional to the weight of the consumer.A consumer may be temporarily deactivated (in which case it won't be returned by
get(), but still retain its share of the resource which will be provided later byget()when it has been reactivated.
- Method
add
Consumer(<ValueType>) add(Consumer(<ValueType>)c)- Description
(Re-)activate a
Consumer.
- Method
add
variantConsumer(<ValueType>) add(int|floatweight,ValueTypeval)- Description
Create a
Consumerwith the weightweightfor the valueval, and add it to the Scheduler.
- Method
adjust_weight
voidadjust_weight(Consumer(<ValueType>)c,intnew_weight)- Description
Adjust the weight value
new_weightof theConsumercin the scheduling table.
- Method
get
Consumer(<ValueType>) get()- Description
Returns the next
Consumerto consume some of the resource.- Returns
Returns a
Consumerif there are any activeConsumersandUNDEFINEDotherwise.- Note
The same
Consumerwill be returned until it has either consumed some of the resource, been removed or anotherConsumerwith lower priority has been added.
- Method
remove
voidremove(Consumer(<ValueType>)c)- Description
Remove the
Consumercfrom the set of active consumers.The consumer may be reactivated by calling
add().
Class ADT.Scheduler.Consumer (< ValueType >)
- Description
A resource consumer.
Active consumers are kept in a (min-)
Heap.
- Variable
pri
floatADT.Scheduler.Consumer.pri- Description
Accumulated deltas and initial priority.
Typically in the range
0.0 .. 2.0, but may temporarily be outside of the range.
- Variable
weight
voidADT.Scheduler.Consumer.weight- Description
Getting
Get the weight of the consumer.
Setting
Get the weight of the consumer.
- Method
consume
voidconsume(floatdelta)- Description
Consume some of the resource.
- Parameter
delta Share of the resource quanta that was actually consumed. Typically
1.0, but other values are supported.This causes the consumer to be reprioritized.
Class ADT.Sequence
- Description
The sequence work similar to an array but has the possibility to insert and remove elements. It also has a more powerful iterator.
- Method
_equal
boolequal(ADT.Sequencefrom,mixedcoll)- Returns
Returns true if the object
collis aSequenceand contains the same values in the same order.
- Method
_get_iterator
ADT.Sequencea;
foreach( a; index; value ) orSequenceIterator_get_iterator(void|intind)- Description
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
- Parameter
ind If an
indvalue is supplied the iterator will be positioned at that index.- Returns
An iterator.
- Method
_insert_element
void_insert_element(intindex,mixedvalue)- Description
Insert an element in the sequence at the position
index, the value at the positionindexand all above will have their index increased by one.- Parameter
index The index to insert the value at.
- Parameter
value The new value.
- Method
_remove_element
mixed_remove_element(intindex)- Description
Remove the values at index
indexfrom the sequence.- Parameter
index The index to remove.
- Returns
The removed value.
- Method
_search
intsearch(ADT.Sequencefrom,mixedvalue,void|intstart)- Description
Search the sequence for a specific value. Return the index of the first value that is equal to
value. If no value was foundUNDEFINEDis returned instead.- Parameter
value The value to find.
- Parameter
start If a start value is supplied it will start searching at the index
start.- Returns
Returns the index of the found value or
UNDEFINED.
- Method
`&
Sequenceres =ADT.Sequence()&coll- Description
And operator Perform an and on this sequence and the
collsequence by only returning those values that is present in both sequences as a newSequence. The remaining values is in the same order as they are in this sequence and the values are compared using `==.- Parameter
coll The sequence to and to this sequence.
- Returns
The result of the and as a new
Sequence.
- Method
`+
Sequenceres =ADT.Sequence()+coll- Description
Addition operator
Append the content of @
collto this sequence and return the results as a newSequence.- Parameter
coll The sequences to append to this sequence.
- Returns
The result of the append as a new
Sequence.
- Method
`-
Sequenceres =ADT.Sequence()-coll- Description
Subtraction operator
Removes those values in this sequence that also are present in @
colland return the results as a newSequence.- Parameter
coll The sequence to subtract from this sequence.
- Returns
The result of the subtraction as a new
Sequence.
- Method
`[]
mixedres =ADT.Sequence()[index]- Description
Index operator.
- Parameter
index The index to get the value for, could be negative to index from the end.
- Returns
The value at the index
index.- Throws
An error if the index is out of range.
- Method
`[]=
ADT.Sequence()[index] =value- Description
Index assign operator. Set the value at the index
indexto bevalue.- Parameter
index The index to set.
- Parameter
value The new value.
- Returns
The new value at the index
index.
- Method
`^
Sequenceres =ADT.Sequence()^coll- Description
Xor operator Perform a xor on this sequence and the
collsequence by returning those values that is present in one of the sequences but not in both sequences as a newSequence. The values are compared using `==.- Parameter
coll The sequence to xor with this sequence.
- Returns
The result of the xor as a new
Sequence.
- Method
`|
Sequenceres =ADT.Sequence()|coll- Description
Or operator Perform an or on this sequence and the
collsequence by returning those values that is present in both sequences as a newSequence. The values are compared using `==.- Parameter
coll The sequence to or with this sequence.
- Returns
The result of the or as a new
Sequence.
- Method
add
voidadd(mixedvalue)- Description
Add a value at the end of the sequence.
- Parameter
value The value to add.
- Method
cast
(array)ADT.Sequence()- Description
Cast operator.
- Parameter
type Casts to this type.
Casts to the following types are supported:
"array"Cast the content of this sequence to an array.
- Returns
An array with the contents of this sequence.
- Method
create
ADT.SequenceADT.Sequence(array|intarg)- Description
Creates a new
Sequencearound the array arg or a newSequencewith the size of arg.
- Method
delete_value
intdelete_value(mixedvalue)- Description
Remove the first occurrence of the value
valuefrom the sequence.- Parameter
value The value to remove from the sequence.
- Returns
The index of the removed element or -1 if there was no value to remove.
- Method
first
SequenceIteratorfirst()- Description
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
- Returns
An iterator positioned at the first element in the sequence.
- Method
last
SequenceIteratorlast()- Description
Create and initiate a new SequenceIterator that could be used to iterate over this sequence.
- Returns
An iterator positioned after the last element in the sequence.
Class ADT.Sequence.SequenceIterator
- Description
This is the iterator for the Sequence. It implements the IndexIterator and the OutputIterator
- Method
_equal
boolequal(ADT.Sequence.SequenceIteratorfrom,mixediter)- Description
Compare this iterator with another iterator.
- Parameter
iter The iterator to compare with.
- Returns
Returns true if both iterators iterates over the same objects and are positioned at the same spot.
- Method
_iterator_next
bool_iterator_next()- Description
Advance to the next position in the sequence.
- Returns
Returns the new position, or
UNDEFINEDif the end of the sequence is reached.- Note
Calling this function when the end of the sequence has already been reached restarts the iterator at the first element of the sequence (if any).
- Method
`+
SequenceIteratorres =ADT.Sequence.SequenceIterator()+steps- Description
Move the iterator
stepssteps forward (negative value onstepswill cause the iterator to move backwards) and return the result as a new iterator.- Returns
A new iterator positioned
stepssteps forward.
- Method
`+=
ADT.Sequence.SequenceIterator()+=steps- Description
Move this iterator
stepssteps forward (negative value onstepswill cause the iterator to move backwards) and return the result.- Returns
This iterator positioned
stepssteps forward.
- Method
`-
SequenceIteratorres =ADT.Sequence.SequenceIterator()-steps- Description
Move the iterator
stepssteps backwards (negative value onstepswill cause the iterator to move forwards) and return the result as a new iterator.- Returns
A new iterator positioned
stepssteps backwards.
- Method
`<
boolres =ADT.Sequence.SequenceIterator()<iter- Description
Less then operator.
- Returns
Returns true if this iterator has a lower index then
iter.
- Method
`>
boolres =ADT.Sequence.SequenceIterator()>iter- Description
Greater then operator.
- Returns
Returns true if this iterator is at a higher index than
iter.
- Method
create
ADT.Sequence.SequenceIteratorADT.Sequence.SequenceIterator(objectsequence,void|intstart)- Description
Creates a new iterator for the sequence
sequence. If start is supplied it will try to position the iterator so that the next iteration starts atstart.
- Method
distance
intdistance(objectiter)- Parameter
iter The iterator to measure the distance to.
- Returns
Returns distance between this iterator and
iter.- Throws
An error if the two iterator could not be compared.
- Method
get_collection
Sequenceget_collection()- Returns
Returns the Sequence this iterator currently iterates over.
- Method
has_next
boolhas_next(void|intsteps)- Returns
Returns true if it is possible to move
stepssteps forwards, ifstepsis not supplied it checks if it is possible to move one step forward.
- Method
has_previous
boolhas_previous(void|intsteps)- Returns
Returns true if it is possible to move
stepssteps backwards, ifstepsis not supplied it checks if it is possible to move one step backward.
Class ADT.Set (< ValueType >)
- Description
ADT.Set implements a datatype for sets. These sets behave much like multisets, except that they are restricted to containing only one instance of each member value.
From a performance viewpoint, it is probably more efficient for a Pike program to use mappings to serve as sets, rather than using an ADT.Set,so ADT.Set is mainly provided for the sake of completeness and code readability.
- Generic
ValueType
__generic__mixedValueType=mixed- Description
Type for the individual members of the set.
- Method
_indices
array(ValueType) indices(ADT.Setarg)- Description
In analogy with multisets, indices() of an ADT.Set givess an array containing all members of the set.
- Method
_sprintf
stringsprintf(stringformat, ... ADT.Setarg ... )- Description
Printable representation of the set.
- Method
_values
array(int(1..)) values(ADT.Setarg)- Description
In analogy with multisets, values() of an ADT.Set givess an array indicating the number of occurrences in the set for each position in the member array returned by indices(). (Most of the time, this is probably rather useless for sets, since the result is an array which just contain 1's, one for each member of the set. Still, this function is provided for consistency.
- Method
`&
this_program(<ValueType>) res =ADT.Set()&other- Description
Intersection. Returns a set containing those values that were present in both the operand sets.
- Method
`-
this_program(<ValueType>) res =ADT.Set()-other- Description
Difference. The expression 'A - B', where A and B are sets, returns all elements in A that are not also present in B.
- Method
`<
boolres =ADT.Set()<other- Description
True subset. A < B returns true if each item in A is also present in B, and B contains at least one item not present in A.
- Method
`==
boolres =ADT.Set()==other- Description
Equality. A == B returns true if all items in A are present in B, and all items in B are present in A. Otherwise, it returns false.
- Method
`>
boolres =ADT.Set()>other- Description
True superset. A > B returns true if each item in B is also present in A, and A contains at least one item not present in B.i
- Method
`[]
boolres =ADT.Set()[item]- Description
Indexing a set with a value V gives 1 if V is a member of the set, otherwise 0.
- Method
`[]=
ADT.Set()[item] =value- Description
Setting an index V to 0 removes V from the set. Setting it to a non-0 value adds V as a member of the set.
- Method
`|
this_program(<mixed>) res =ADT.Set()|other- Description
Union. Returns a set containing all elements present in either or both of the operand sets.
- Method
create
ADT.SetADT.Set(void|ADT.Set|array(ValueType)|multiset(ValueType)|mapping(ValueType:mixed)initial_data)- Description
Create an ADT.Set, optionally initialized from another ADT.Set or a compatible type. If no initial data is given, the set will start out empty.
- Method
filter
this_program(<ValueType>) filter(function(ValueType:mixed)f)- Description
Return a filtered version of the set, containing only those members for which the filtering function
freturned true.The filtering function is called with a single mixed-type argument which is the member value to be checked.
- Method
filter_destructively
this_program(<ValueType>) filter_destructively(function(ValueType:mixed)f)- Description
Destructively filter the set, i.e. remove every element for which the filtering function
freturns 0, and then return the set.The filtering function is called with a single mixed-type argument which is the member value to be checked.
- Note
CAVEAT EMPTOR: This function was just a duplicate of
filter()in Pike 8.0 and earlier.
- Method
map
array(mixed) map(function(ValueType:mixed)f)- Description
Map the values of a set: calls the map function
fonce for each member of the set, returning an array which contains the result of each one of those function calls. Note that since a set isn't ordered, the values in the returned array will be in more or less random order. If you need to know which member value produced which result, you have to make that a part of what the filtering function returns.The filtering function
fis called with a single, mixed-type argument which is the member value to be mapped.
- Method
subset
boolsubset(ADT.Setother)- Description
Subset. A <= B returns true if all items in A are also present in B.
Class ADT.Stack (< ElementType >)
- Description
This class implements a simple stack. Instead of adding and removing elements to an array, and thus making it vary in size for every push and pop operation, this stack tries to keep the stack size constant. If however the stack risks to overflow, it will allocate double its current size, i.e. pushing an element on an full 32 slot stack will result in a 64 slot stack with 33 elements.
- Generic
ElementType
__generic__mixedElementType=mixed- Description
Type for the elements on the stack.
- Method
_search
intsearch(ADT.Stackfrom,mixeditem)- Description
Return the stack-depth to
item.This function makes it possible to use eg
search()andhas_value()on the stack.
- Method
_sizeof
intsizeof(ADT.Stackarg)- Description
sizeofon a stack returns the number of entries in the stack.
- Method
_values
array(ElementType) values(ADT.Stackarg)- Description
valueson a stack returns all the entries in the stack, in order.
- Method
`+
this_program(<mixed>) res =ADT.Stack()+s- Description
A stack added with another stack yields a new stack with all the elements from both stacks, and the elements from the second stack at the top of the new stack.
- Method
create
ADT.StackADT.Stack(int(1..)|voidinitial_size)- Description
An initial stack size can be given when a stack is cloned. The default value is 32.
- Method
peek
ElementTypepeek(int|voidoffset)- Description
Returns an element from the stack, without popping it.
- Parameter
offset The number of elements from the top of the stack to skip.
- Throws
Throws an error if called on an empty stack.
- See also
top()
- Method
pop
variantarray(ElementType) pop(int(1..)val)- Description
Pops and returns an array with the top
valentries from the stack. All popped entries are freed from the stack.seealso
quick_pop()
- Method
pop_to
voidpop_to(intdepth)- Description
Pops entries from the stack until the specified
depthis reached. The popped entries are not actually freed, only the stack pointer is moved.- See also
quick_pop()
- Method
quick_pop
voidquick_pop(void|intval)- Description
Pops
valentries from the stack, or one entry if no value is given. The popped entries are not actually freed, only the stack pointer is moved.- See also
pop(),pop_to()
- Method
reset
voidreset(int(1..)|voidinitial_size)- Description
Empties the stack, resets the stack pointer and shrinks the stack size to the given value or 32 if none is given.
- See also
create
- Method
set_stack
voidset_stack(array(ElementType)stack)- Description
Sets the stacks content to the provided array.
Class ADT.Struct
- Description
Implements a struct which can be used for serialization and deserialization of data.
- Example
class ID3 { inherit ADT.Struct; Item head = Chars(3); Item title = Chars(30); Item artist = Chars(30); Item album = Chars(30); Item year = Chars(4); Item comment = Chars(30); Item genre = Byte(); }
Stdio.File f = Stdio.File("foo.mp3"); f->seek(-128); ADT.Struct tag = ID3(f); if(tag->head=="TAG") { write("Title: %s\n", tag->title); tag->title = "A new title" + "\0"*19; f->seek(-128); f->write( (string)tag ); }
- Example
class HollerithString { inherit ADT.Struct; Item strlen = Word(); Item str = Chars(strlen); }
- Method
_indices
array(string) indices(ADT.Structarg)- Description
The indices of a struct is the name of the struct items.
- Method
_sizeof
intsizeof(ADT.Structarg)- Description
The size of the struct object is the number of bytes allocated for the struct.
- Method
_values
arrayvalues(ADT.Structarg)- Description
The values of a struct is the values of the struct items.
- Method
`[]
Method `-> mixedres =ADT.Struct()[item]mixedres =ADT.Struct()->X- Description
The struct can be indexed by item name to get the associated value.
- Method
`[]=
Method `->= ADT.Struct()[item] = yADT.Struct()->X = y- Description
It is possible to assign a new value to a struct item by indexing it by name and assign a value.
- Method
cast
(int)ADT.Struct()
(float)ADT.Struct()
(string)ADT.Struct()
(array)ADT.Struct()
(mapping)ADT.Struct()
(multiset)ADT.Struct()- Description
The struct can be casted into a string, which is eqivivalent to running
encode, or into an array. When casted into an array each array element is the encoded value of that struct item.
- Method
create
ADT.StructADT.Struct(void|string|Stdio.Filedata)- Parameter
data Data to be decoded and populate the struct. Can either be a file object or a string.
- Method
decode
voiddecode(string|Stdio.Filedata)- Description
Decodes
dataaccording to the struct and populates the struct variables. Thedatacan either be a file object or a string.
- Method
encode
stringencode()- Description
Serializes the struct into a string. This string is equal to the string fed to
decodeif nothing in the struct has been altered.
Class ADT.Struct.Byte
- Description
One byte, integer value between 0 and 255.
Class ADT.Struct.Chars
- Description
A string of bytes.
- Method
create
ADT.Struct.CharsADT.Struct.Chars(int|Itemsize,void|stringvalue)- Description
sizeis the number of bytes that are part of this struct item, or optionally an earlier Item that will be looked up in runtime. The initial value of the char string isvalueor, if not provided, a string of zero bytes.
Class ADT.Struct.Drow
- Description
One word (2 bytes) in intel order, integer value between 0 and 65535.
- See also
Word
Class ADT.Struct.Gnol
- Description
One longword (4 bytes) in intel order, integer value between 0 and 2^32.
- See also
Long
Class ADT.Struct.Item
- Description
Interface class for struct items.
Class ADT.Struct.Long
- Description
One longword (4 bytes) in network order, integer value between 0 and 2^32.
- See also
Gnol
Class ADT.Struct.SByte
- Description
One byte, signed integer value between -128 and 127.
Class ADT.Struct.SLong
- Description
One longword (4 bytes) in network order, signed integer value -(2^31) <= x < 2^31-1.
Class ADT.Struct.SWord
- Description
One word (2 bytes) in network order, signed integer value between 0 and 65535.
Class ADT.Struct.Word
- Description
One word (2 bytes) in network order, integer value between 0 and 65535.
- See also
Drow
Class ADT.TreeScheduler (< ValueType >)
- Description
This class implements an hierarchial quantized resource scheduler.
It differs from
Schedulerby the [Consumer]s making up a dependency tree.Active consumers closer to the root will receive the resource before their children.
Implements most of RFC 7540 section 5.3.
- See also
Scheduler
- Variable
root
Consumer(<ValueType>)|zeroADT.TreeScheduler.root- Description
The root of the
Customerdependency tree.- Note
Note that the root is never active (ie added to the Scheduler).
Customers that don't have an explicit dependency depend onroot.
- Method
add
variantConsumer(<ValueType>) add(int|floatweight,mixedval,Consumer(<ValueType>)parent)- Description
Create a
Consumerdepending onparentwith the weightweightfor the valueval, and add it to the Scheduler.
Class ADT.TreeScheduler.Consumer (< ValueType >)
- Description
A resource consumer.
All consumers (both active and inactive) are nodes in a dependency tree. This means that to avoid excessive garbage
detach()must be called in consumers that are no longer to be used.Active consumers are kept in a (min-)
Heap.
- Variable
children
array(Consumer(<ValueType>)) ADT.TreeScheduler.Consumer.children- Description
Consumers that depend on us.
- Variable
parent
Consumer(<ValueType>)|zeroADT.TreeScheduler.Consumer.parent- Description
Consumerthat we depend on.
- Method
create
ADT.TreeScheduler.ConsumerADT.TreeScheduler.Consumer(int|floatweight,ValueTypev,Consumer(<ValueType>)|voidparent)
- Method
detach
voiddetach()- Description
Detach from the tree.
Any children are moved to our parent and their weights adjusted to keep their priorities.
- Note
If the consumer was active it will be deactivated.
- Method
reparent_siblings
voidreparent_siblings()- Description
Reparent all sibling
Consumers, so that we become the only child of our parent.- See also
set_parent()
- Method
set_parent
voidset_parent(Consumer(<ValueType>)new_parent,int|floatweight)- Description
Change to a new parent.
- Parameter
new_parent Consumerthis object depends on. We will only get returned byget()whennew_parentis inactive (ieremoved).- Parameter
weight New weight.
- Note
If
new_parentdepends on us, it will be moved to take our place in depending on our old parent.- Note
To perform the exclusive mode reparent from RFC 7540 figure 5, call
reparent_siblings()after this function.- See also
detach(),remove(),create(),reparent_siblings()
Class ADT.struct
- Description
String buffer with the possibility to read and write data as they would be formatted in structs.
- Deprecated
Replaced by
Stdio.Buffer.
- Method
add_data
this_programadd_data(string(8bit)s)- Description
Adds the data
sverbatim to the end of the buffer.
- Method
contents
string(8bit)contents()- Description
Trims the buffer to only contain the data after the read pointer and returns the contents of the buffer.
- Method
create
ADT.structADT.struct(void|string(8bit)s)- Description
Create a new buffer, optionally initialized with the value
s.
- Method
get_bignum
Gmp.mpzget_bignum(int(1..)|voidlen)- Description
Reads a bignum written by
put_bignumfrom the buffer.
- Method
get_fix_string
string(8bit)get_fix_string(intlen)- Description
Reads a fixed sized string of length
lenfrom the buffer.
- Method
get_fix_uint_array
array(int) get_fix_uint_array(int(8bit)item_size,intsize)- Description
Reads an array of integers as written by
put_fix_uint_arrayfrom the buffer.
- Method
get_rest
string(8bit)get_rest()- Description
Get the remaining data from the buffer and clears the buffer.
- Method
get_var_string
string(8bit)get_var_string(int(0..)len)- Description
Reads a string written by
put_var_stringfrom the buffer.
- Method
get_var_uint_array
array(int) get_var_uint_array(int(8bit)item_size,int(0..)len)- Description
Reads an array of integers as written by
put_var_uint_arrayfrom the buffer.
- Method
put_bignum
this_programput_bignum(Gmp.mpzi,int(1..)|voidlen_width)- Description
Appends a bignum
ias a variable string preceded with an unsigned integer of the sizelen_widthdeclaring the length of the string.len_widthdefaults to 2.
- Method
put_fix_string
this_programput_fix_string(string(8bit)s)- Description
Appends the fix sized string
sto the buffer.
- Method
put_fix_uint_array
this_programput_fix_uint_array(array(int)data,int(8bit)item_size)- Description
Appends an array of unsigned integers of width
item_sizeto the buffer.
- Method
put_uint
this_programput_uint(inti,int(0..)len)- Description
Appends an unsigned integer in network order to the buffer.
- Parameter
i Unsigned integer to append.
- Parameter
len Length of integer in bytes.
- Method
put_var_string
this_programput_var_string(string(8bit)s,int(0..)len_width)- Description
Appends a variable string
spreceded with an unsigned integer of the sizelen_widthdeclaring the length of the string. The stringsshould be 8 bits wide.
- Method
put_var_string_array
this_programput_var_string_array(array(string(8bit))data,int(0..)item_size,int(0..)len)- Description
Appends an array of variable length strings with
item_sizebytes hollerith coding, prefixed by alenbytes large integer declaring the total size of the array in bytes.
Module ADT.CritBit
- Description
This module offers CritBit tree implementations for different key types.
- Note
These CritBit trees support prefixes as proper keys. Hence they should really be called Tries.
- Method
Tree
objectTree(void|string|program|mappingtype)- Description
Creates a CritBit tree for keys of type
type. If no argument is given, an instance ofADT.CritBit.StringTreeis returned. Supported types are"string","int","float","ipv4"andCalendar.TimeRange.
- Method
sort_ipv4
array(string) sort_ipv4(array(string)a,array...data)- Description
Sorts an ARRAY OF IPv4-Adresses (and optional netmasks) given in dotted decimal representation with the /23 netmask notation.
- Example
>array(string) a =({"127.0.0.121",>"127.0.0.0/16",>"127.0.0.1/8",>"127.0.0.0/8",>"128.0.0.0/1",>"192.168.21.3",>"8.8.8.8"});> write("%O\n", CritBit.sort_ipv4(a));({/* 7 elements */"8.8.8.8","127.0.0.0/8","127.0.0.0/16","127.0.0.1/8","127.0.0.121","128.0.0.0/1","192.168.21.3"})
Class ADT.CritBit.DateTree
- Method
decode_key
int|objectdecode_key(inti)- Description
Decodes an integer back to a
Calendar.TimeRangeobject. Keeps a mapping of all keys stored in the tree to transform back.
- Method
decode_key
Class ADT.CritBit.FloatTree
- Description
This class implements a CritBit-tree/trie that can be used as a mapping-like data structure. Values of
float|intcan be used as indices, while any possible type (alsomixed) can be stored.CritBit trees are prefixed based search trees that allow for fast random access as well as prefix and range based lookups. Keys are stored in alphabetical order and can be iterated over using
foreach. Other than that, it can be used likemapping(float|int:mixed).- Example
ADT.CritBit.FloatTree tree =ADT.CritBit.FloatTree();float|int key1 = 12.0; tree[key1]=({ 4, 5, 6 }); tree[key1];// now is ({ 4, 5, 6 }) m_delete(tree, key1);// tree is empty again- Example
ADT.CritBit.FloatTree tree =ADT.CritBit.FloatTree();array(float|int) a =({ 80.4, 99.9, 14.2 });foreach(a;int idx;float|int val){ tree[val]= idx;}foreach(tree;float|int key;mixed val){// in here the keys will be reached in order 14.2, 80.4 and 99.9.}- Example
ADT.CritBit.FloatTree tree =ADT.CritBit.FloatTree();array(float|int) a =({ 80.4, 99.9, 14.2 });foreach(a;int idx;float|int val){ tree[val]= idx;}foreach(ADT.CritBit.FloatTree.Iterator (tree,-1);float|int key;mixed val){// in here the keys will be reached in order 99.9, 80.4 and 14.2.}- See also
ADT.CritBit.FloatTree.Iterator
- Method
_indices
arrayindices(ADT.CritBit.FloatTreearg)- Description
Returns a sorted array of indices of the
FloatTree.
- Method
_random
arrayrandom(ADT.CritBit.FloatTreearg)- Description
Get a random entry.
- Returns
An array
({ key, value }).
- Method
_sizeof
intsizeof(ADT.CritBit.FloatTreearg)- Description
Gives the number of entries in the
FloatTree.
- Method
_values
arrayvalues(ADT.CritBit.FloatTreearg)- Description
Returns an array of values of the
FloatTreeobject. The returned array matches_indicesso thatmkmapping(indices(tree), values(tree))would create a mapping with the same contents as thisFloatTree.
- Method
`+
mixedres =ADT.CritBit.FloatTree()+o- Description
Add callback. Returns the union of two trees.
- Method
`-
mixedres =ADT.CritBit.FloatTree()-o- Description
Sub[s]tract two trees from each other (key-wise).
- Method
bkey
stringbkey(mixedkey)- Description
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
- Method
cast
(mapping)ADT.CritBit.FloatTree()- Description
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
- Method
create
ADT.CritBit.FloatTreeADT.CritBit.FloatTree(array|mapping|voido)- Description
Create a FloatTree from o.
- Method
encode_key
Method decode_key float|intencode_key(mixedo)mixeddecode_key(float|into)- Description
These callbacks can be implemented when inheriting FloatTree in order to allow for arbitrary key types.
encode_keyis similar to thelfun::_hash()callback. This only works as expected when it is possible to implement a unique representation for keys. These callbacks are called everytime a key is stored or indexed in the tree.
- Method
get_subtree
FloatTreeget_subtree(void|mixedkey)- Description
Get a copy of the subtree starting at prefix
key.
- Method
next
float|intnext(mixedcurrent)- Description
Get the key after
currentin lexicographical order.
- Method
nth
mixednth(int(0..)n)- Description
Get the
nth entry in order.- Returns
An array
({ key, value }).
- Method
previous
float|intprevious(mixedcurrent)- Description
Get the key before
currentin lexicographical order.
Class ADT.CritBit.FloatTree._get_iterator
- Description
Iterator class for FloatTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling
foreachon an object of FloatTree. Inforeachthe iterator runs over all elements from the first to the last.- See also
predef::Iteratorfor a description of the interface.
Class ADT.CritBit.IPv4Tree
- Description
This class implements a CritBit-tree/trie that can be used as a mapping-like data structure. Values of
stringcan be used as indices, while any possible type (alsomixed) can be stored.CritBit trees are prefixed based search trees that allow for fast random access as well as prefix and range based lookups. Keys are stored in alphabetical order and can be iterated over using
foreach. Other than that, it can be used likemapping(string:mixed).- Example
ADT.CritBit.IPv4Tree tree =ADT.CritBit.IPv4Tree();string key1 ="127.0.0.0/8"; tree[key1]="reject"; tree[key1];// now is "reject" m_delete(tree, key1);// tree is empty again- Example
ADT.CritBit.IPv4Tree tree =ADT.CritBit.IPv4Tree();array(string) a =({"10.243.7.1","127.0.0.1/8","172.16.5.2"});foreach(a;int idx;string val){ tree[val]= idx;}foreach(tree;string key;mixed val){// in here the keys will be reached in order "10.243.7.1", "127.0.0.1/8" and "172.16.5.2".}- Example
ADT.CritBit.IPv4Tree tree =ADT.CritBit.IPv4Tree();array(string) a =({"10.243.7.1","127.0.0.1/8","172.16.5.2"});foreach(a;int idx;string val){ tree[val]= idx;}foreach(ADT.CritBit.IPv4Tree.Iterator (tree,-1);string key;mixed val){// in here the keys will be reached in order "172.16.5.2", "127.0.0.1/8" and "10.243.7.1".}- See also
ADT.CritBit.IPv4Tree.Iterator
- Method
_indices
arrayindices(ADT.CritBit.IPv4Treearg)- Description
Returns a sorted array of indices of the
IPv4Tree.
- Method
_random
arrayrandom(ADT.CritBit.IPv4Treearg)- Description
Get a random entry.
- Returns
An array
({ key, value }).
- Method
_sizeof
intsizeof(ADT.CritBit.IPv4Treearg)- Description
Gives the number of entries in the
IPv4Tree.
- Method
_values
arrayvalues(ADT.CritBit.IPv4Treearg)- Description
Returns an array of values of the
IPv4Treeobject. The returned array matches_indicesso thatmkmapping(indices(tree), values(tree))would create a mapping with the same contents as thisIPv4Tree.
- Method
`+
mixedres =ADT.CritBit.IPv4Tree()+o- Description
Add callback. Returns the union of two trees.
- Method
`-
mixedres =ADT.CritBit.IPv4Tree()-o- Description
Sub[s]tract two trees from each other (key-wise).
- Method
bkey
stringbkey(mixedkey)- Description
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
- Method
cast
(mapping)ADT.CritBit.IPv4Tree()- Description
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
- Method
common_prefix
string|intcommon_prefix()- Description
Returns the common prefix of all keys. If the tree has no elements,
UNDEFINEDis returned.
- Method
create
ADT.CritBit.IPv4TreeADT.CritBit.IPv4Tree(array|mapping|voido)- Description
Create a IPv4Tree from o.
- Method
encode_key
Method decode_key stringencode_key(mixedo)mixeddecode_key(stringo)- Description
These callbacks can be implemented when inheriting IPv4Tree in order to allow for arbitrary key types.
encode_keyis similar to thelfun::_hash()callback. This only works as expected when it is possible to implement a unique representation for keys. These callbacks are called everytime a key is stored or indexed in the tree.
- Method
get_subtree
IPv4Treeget_subtree(void|mixedkey)- Description
Get a copy of the subtree starting at prefix
key.
- Method
nth
mixednth(int(0..)n)- Description
Get the
nth entry in order.- Returns
An array
({ key, value }).
- Method
previous
stringprevious(mixedcurrent)- Description
Get the key before
currentin lexicographical order.
Class ADT.CritBit.IPv4Tree._get_iterator
- Description
Iterator class for IPv4Tree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling
foreachon an object of IPv4Tree. Inforeachthe iterator runs over all elements from the first to the last.- See also
predef::Iteratorfor a description of the interface.
Class ADT.CritBit.IntTree
- Description
This class implements a CritBit-tree/trie that can be used as a mapping-like data structure. Values of
intcan be used as indices, while any possible type (alsomixed) can be stored.CritBit trees are prefixed based search trees that allow for fast random access as well as prefix and range based lookups. Keys are stored in alphabetical order and can be iterated over using
foreach. Other than that, it can be used likemapping(int:mixed).- Example
ADT.CritBit.IntTree tree =ADT.CritBit.IntTree();int key1 = 12; tree[key1]=({ 1, 2 ,3 }); tree[key1];// now is ({ 1, 2 ,3 }) m_delete(tree, key1);// tree is empty again- Example
ADT.CritBit.IntTree tree =ADT.CritBit.IntTree();array(int) a =({ 1025, 15000, 3 });foreach(a;int idx;int val){ tree[val]= idx;}foreach(tree;int key;mixed val){// in here the keys will be reached in order 3, 1025 and 15000.}- Example
ADT.CritBit.IntTree tree =ADT.CritBit.IntTree();array(int) a =({ 1025, 15000, 3 });foreach(a;int idx;int val){ tree[val]= idx;}foreach(ADT.CritBit.IntTree.Iterator (tree,-1);int key;mixed val){// in here the keys will be reached in order 15000, 1025 and 3.}- See also
ADT.CritBit.IntTree.Iterator
- Method
_indices
arrayindices(ADT.CritBit.IntTreearg)- Description
Returns a sorted array of indices of the
IntTree.
- Method
_random
arrayrandom(ADT.CritBit.IntTreearg)- Description
Get a random entry.
- Returns
An array
({ key, value }).
- Method
_sizeof
intsizeof(ADT.CritBit.IntTreearg)- Description
Gives the number of entries in the
IntTree.
- Method
_values
arrayvalues(ADT.CritBit.IntTreearg)- Description
Returns an array of values of the
IntTreeobject. The returned array matches_indicesso thatmkmapping(indices(tree), values(tree))would create a mapping with the same contents as thisIntTree.
- Method
`+
mixedres =ADT.CritBit.IntTree()+o- Description
Add callback. Returns the union of two trees.
- Method
`-
mixedres =ADT.CritBit.IntTree()-o- Description
Sub[s]tract two trees from each other (key-wise).
- Method
bkey
stringbkey(mixedkey)- Description
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
- Method
cast
(mapping)ADT.CritBit.IntTree()- Description
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
- Method
create
ADT.CritBit.IntTreeADT.CritBit.IntTree(array|mapping|voido)- Description
Create a IntTree from o.
- Method
encode_key
Method decode_key intencode_key(mixedo)mixeddecode_key(into)- Description
These callbacks can be implemented when inheriting IntTree in order to allow for arbitrary key types.
encode_keyis similar to thelfun::_hash()callback. This only works as expected when it is possible to implement a unique representation for keys. These callbacks are called everytime a key is stored or indexed in the tree.
- Method
get_subtree
IntTreeget_subtree(void|mixedkey)- Description
Get a copy of the subtree starting at prefix
key.
- Method
nth
mixednth(int(0..)n)- Description
Get the
nth entry in order.- Returns
An array
({ key, value }).
- Method
previous
intprevious(mixedcurrent)- Description
Get the key before
currentin lexicographical order.
Class ADT.CritBit.IntTree._get_iterator
- Description
Iterator class for IntTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling
foreachon an object of IntTree. Inforeachthe iterator runs over all elements from the first to the last.- See also
predef::Iteratorfor a description of the interface.
Class ADT.CritBit.RangeSet
- Description
Data structure representing a set of disjunct
ADT.Intervalobjects. Can be thought of as an interval with gaps.
Class ADT.CritBit.Reverse
Class ADT.CritBit.StringTree
- Description
This class implements a CritBit-tree/trie that can be used as a mapping-like data structure. Values of
stringcan be used as indices, while any possible type (alsomixed) can be stored.CritBit trees are prefixed based search trees that allow for fast random access as well as prefix and range based lookups. Keys are stored in alphabetical order and can be iterated over using
foreach. Other than that, it can be used likemapping(string:mixed).- Example
ADT.CritBit.StringTree tree =ADT.CritBit.StringTree();string key1 ="foo"; tree[key1]=({ 7, 8, 9 }); tree[key1];// now is ({ 7, 8, 9 }) m_delete(tree, key1);// tree is empty again- Example
ADT.CritBit.StringTree tree =ADT.CritBit.StringTree();array(string) a =({"fooo","bar","ahead"});foreach(a;int idx;string val){ tree[val]= idx;}foreach(tree;string key;mixed val){// in here the keys will be reached in order "ahead", "bar" and "foo".}- Example
ADT.CritBit.StringTree tree =ADT.CritBit.StringTree();array(string) a =({"fooo","bar","ahead"});foreach(a;int idx;string val){ tree[val]= idx;}foreach(ADT.CritBit.StringTree.Iterator (tree,-1);string key;mixed val){// in here the keys will be reached in order "foo", "bar" and "ahead".}- See also
ADT.CritBit.StringTree.Iterator
- Method
_indices
arrayindices(ADT.CritBit.StringTreearg)- Description
Returns a sorted array of indices of the
StringTree.
- Method
_random
arrayrandom(ADT.CritBit.StringTreearg)- Description
Get a random entry.
- Returns
An array
({ key, value }).
- Method
_sizeof
intsizeof(ADT.CritBit.StringTreearg)- Description
Gives the number of entries in the
StringTree.
- Method
_values
arrayvalues(ADT.CritBit.StringTreearg)- Description
Returns an array of values of the
StringTreeobject. The returned array matches_indicesso thatmkmapping(indices(tree), values(tree))would create a mapping with the same contents as thisStringTree.
- Method
`+
mixedres =ADT.CritBit.StringTree()+o- Description
Add callback. Returns the union of two trees.
- Method
`-
mixedres =ADT.CritBit.StringTree()-o- Description
Sub[s]tract two trees from each other (key-wise).
- Method
bkey
stringbkey(mixedkey)- Description
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
- Method
cast
(mapping)ADT.CritBit.StringTree()- Description
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
- Method
common_prefix
string|intcommon_prefix()- Description
Returns the common prefix of all keys. If the tree has no elements,
UNDEFINEDis returned.
- Method
create
ADT.CritBit.StringTreeADT.CritBit.StringTree(array|mapping|voido)- Description
Create a StringTree from o.
- Method
encode_key
Method decode_key stringencode_key(mixedo)mixeddecode_key(stringo)- Description
These callbacks can be implemented when inheriting StringTree in order to allow for arbitrary key types.
encode_keyis similar to thelfun::_hash()callback. This only works as expected when it is possible to implement a unique representation for keys. These callbacks are called everytime a key is stored or indexed in the tree.
- Method
get_subtree
StringTreeget_subtree(void|mixedkey)- Description
Get a copy of the subtree starting at prefix
key.
- Method
nth
mixednth(int(0..)n)- Description
Get the
nth entry in order.- Returns
An array
({ key, value }).
- Method
previous
stringprevious(mixedcurrent)- Description
Get the key before
currentin lexicographical order.
Class ADT.CritBit.StringTree._get_iterator
- Description
Iterator class for StringTree trees. Supports iterating over ranges with arbitrary stepping and direction.
This is used by default when calling
foreachon an object of StringTree. Inforeachthe iterator runs over all elements from the first to the last.- See also
predef::Iteratorfor a description of the interface.
Module ADT.Relation
Class ADT.Relation.Binary (< LeftType, RightType >)
- Description
An abstract data type for binary relations.
This datatype implements something similar to a set of tuples <left, right>, or a multi-valued mapping.
- Generic
LeftType
__generic__mixedLeftType=mixed- Description
Type for the left values in the relation.
- Generic
RightType
__generic__mixedRightType=LeftType- Description
Type for the right values in the relation.
- Method
_sizeof
int(0..)sizeof(ADT.Relation.Binaryarg)- Description
Returns the number of relation entries in the relation. (Or with other words: the number of relations in the relation set.)
- Method
`&
ADT.Relation.Binary(<LeftType,RightType>) res =ADT.Relation.Binary()&rel- Description
The expression `´
rel1 & rel2returns a new relation which has those and only those relation entries that are present in both rel1 and rel2.
- Method
`()
boolres =ADT.Relation.Binary()()- Description
Does the same as the
containsfunction: returns true if the relation "leftRright" exists, and otherwise false.
- Method
`+
Method `| ADT.Relation.Binary(<LeftType,RightType>) res =ADT.Relation.Binary()+relADT.Relation.Binary(<LeftType,RightType>) res =ADT.Relation.Binary()|rel- Description
The expressions
rel1 | rel2andrel1 + rel2return a new relation which has all the relation entries present in rel1, or rel2, or both.
- Method
`-
ADT.Relation.Binary(<LeftType,RightType>) res =ADT.Relation.Binary()-rel- Description
The expression
rel1 - rel2returns a new relation which has those and only those relation entries that are present in rel1 and not present in rel2.
- Method
add
this_program(<LeftType,RightType>) add(LeftTypeleft,RightTyperight)- Description
Adds "
leftRright" as a member of the relation. Returns the same relation.
- Method
contains
boolcontains(LeftTypeleft,RightTyperight)- Description
Return true/false: does the relation "
leftRright" exist?
- Method
create
ADT.Relation.BinaryADT.Relation.Binary(void|mixedid,void|mapping(LeftType:RightType)|this_program(<LeftType,RightType>)initial)- Description
Initialize a new
ADT.Relation.Binaryobject.- Parameter
id Identifier for the relation.
- Parameter
initial Initial contents of the relation.
- See also
get_id()
- Method
filter
ADT.Relation.Binary(<LeftType,RightType>) filter(function(LeftType,RightType:mixed)f)- Description
Filters the entries in the relation, and returns a relation with all those entries for which the filtering function
freturned true. The functionfgets two arguments: the left and the right value for every entry in the relation.- See also
filter_destructively()
- Method
filter_destructively
this_program(<LeftType,RightType>) filter_destructively(function(LeftType,RightType:mixed)f)- Description
Filters the entries in the relation destructively, removing all entries for which the filtering function
freturns false. The functionfgets two arguments: the left and the right value for each entry in the relation.- See also
filter()
- Method
find_shortest_path
array(LeftType|RightType)|zerofind_shortest_path(LeftType|RightTypefrom,LeftType|RightTypeto,multiset(LeftType|RightType)|voidavoiding)- Description
Assuming the relation's domain and range sets are equal, and that the relation xRy means "there is a path from node x to node y",
find_shortest_pathattempts to find a path with a minimum number of steps from one given node to another. The path is returned as an array of nodes (including the starting and ending node), or 0 if no path was found. If several equally short paths exist, one of them will be chosen pseudorandomly.Trying to find a path from a node to itself will always succeed, returning an array of one element: the node itself. (Or in other words, a path with no steps, only a starting/ending point).
The argument
avoidingis either0(or omitted), or a multiset of nodes that must not be part of the path.
- Method
get_id
mixedget_id()- Description
Return the ID value which was given as first argument to create().
- Method
make_symmetric
this_program(<LeftType|RightType,RightType|LeftType>) make_symmetric()- Description
Makes the relation symmetric, i.e. makes sure that if xRy is part of the relation set, then yRx should also be a part of the relation set.
- Note
This operation modifies the current object.
- Method
map
arraymap(function(LeftType,RightType:mixed)f)- Description
Maps every entry in the relation. The function f gets two arguments: the left and the right relation value. Returns an array with the return values of f for each and every mapped entry.
Note: since the entries in the relation are not ordered, the returned array will have its elements in no particular order. If you need to know which relation entry produced which result in the array, you have to make that information part of the value that
freturns.
Module ADT.Table
- Description
ADT.Table is a generic module for manipulating tables.
Each table contains one or several columns. Each column is associated with a name, the column name. Optionally, one can provide a column type. The Table module can do a number of operations on a given table, like computing the sum of a column, grouping, sorting etc.
All column references are case insensitive. A column can be referred to by its position (starting from zero). All operations are non-destructive. That means that a new table object will be returned after, for example, a sort.
Class ADT.Table.table
- Description
The table base-class.
- Method
_indices
array(string) indices(ADT.Table.tablearg)- Description
This method returns the column names for the table. The case used when the table was created will be returned.
- Method
_sizeof
intsizeof(ADT.Table.tablearg)- Description
This method returns the number of rows in the table.
- Method
_values
array(array) values(ADT.Table.tablearg)- Description
This method returns the contents of a table as a two dimensional array. The format is an array of rows. Each row is an array of columns.
- Method
`==
boolres =ADT.Table.table()==table- Description
This method compares two tables. They are equal if the contents of the tables and the column names are equal. The column name comparison is case insensitive.
- Method
append_bottom
this_programappend_bottom(objecttable)- Description
This method appends two tables. The table given as an argument will be added at the bottom of the current table. Note, the column names must be equal. The column name comparison is case insensitive.
- Method
append_right
this_programappend_right(objecttable)- Description
This method appends two tables. The table given as an argument will be added on the right side of the current table. Note that the number of rows in both tables must be equal.
- Method
col
arraycol(int|stringcolumn)- Description
This method returns the contents of a given column as an array.
- Method
create
ADT.Table.tableADT.Table.table(array(array)table,array(string)column_names,array(mapping(string:string))|voidcolumn_types)- Description
The
ADT.Table.tableclass takes two or three arguments:- Parameter
table The first argument is a two-dimensional array consisting of one array of columns per row. All rows must have the same number of columns as specified in
column_names.- Parameter
column_names This argument is an array of column names associated with each column in the table. References by column name are case insensitive. The case used in
column_nameswill be used when the table is displayed. A column can also be referred to by its position, starting from zero.- Parameter
column_types This is an optional array of mappings. The column type information is only used when displaying the table. Currently, only the keyword
"type"is recognized. The type can be specified as"text"or"num"(numerical). Text columns are left adjusted, whereas numerical columns are right adjusted. If a mapping in the array is 0 (zero), it will be assumed to be a text column. Ifcolumn_typesis omitted, all columns will displayed as text.See
ADT.Table.ASCII.encode()on how to display a table.- See also
ADT.Table.ASCII.encode()
- Method
decode
objectdecode(strings)- Description
This method returns a table object from a binary string representation of a table, as returned by
encode().
- Method
distinct
this_programdistinct(int|string...columns)- Description
This method groups by the given columns and returns a table with only unique rows. When no columns are given, all rows will be unique. A new table object will be returned.
- Method
encode
stringencode()- Description
This method returns a binary string representation of the table. It is useful when one wants to store a the table, for example in a file.
- Method
group
this_programgroup(mapping(int|string:function(:void))|function(:void)f,mixed...args)- Description
This method calls the function
ffor each column each time a non uniqe row will be joined. The table will be grouped by the columns not listed. The result will be returned as a new table object.
- Method
limit
this_programlimit(intn)- Description
This method truncates the table to the first
nrows and returns a new object.
- Method
map
objectmap(function(:void)f,array(int|string)|int|stringcolumns,mixed...args)- Description
This method calls the function
ffor all rows in the table. The value returned will replace the values in the columns given as argument to map. If the function returns an array, several columns will be replaced. Otherwise the first column will be replaced. The result will be returned as a new table object.
- Method
remove
this_programremove(int|string...columns)- Description
Like
select(), but the givencolumnswill not be in the resulting table.
- Method
rename
this_programrename(string|intfrom,stringto)- Description
This method renames the column named
fromtotoand returns a new table object. Note thatfromcan be the column position.
- Method
reverse
protectedthis_programreverse()- Description
This method reverses the rows of the table and returns a new table object.
- Method
row
arrayrow(introw_number)- Description
This method returns the contents of a given row as an array.
- Method
select
this_programselect(int|string...columns)- Description
This method returns a new table object with the selected columns only.
- Method
sort
this_programsort(int|string...columns)- Description
This method sorts the table in ascendent order on one or several columns and returns a new table object. The left most column is sorted last. Note that the sort is stable.
- See also
rsort()
- Method
sum
this_programsum(int|string...columns)- Description
This method sums all equal rows. The table will be grouped by the columns not listed. The result will be returned as a new table object.
- Method
type
mappingtype(int|stringcolumn,void|mappingtype)- Description
This method gives the type for the given
column.If a second argument is given, the old type will be replaced with
type. The column type is only used when the table is displayed. The format is as specified increate().
- Method
where
this_programwhere(array(int|string)|int|stringcolumns,function(:void)f,mixed...args)- Description
This method calls the function for each row. If the function returns zero, the row will be thrown away. If the function returns something non-zero, the row will be kept. The result will be returned as a new table object.
Module ADT.Table.ASCII