10. Specific Datatype Modules

  Module String


Method implode_nicely

string String.implode_nicely(array(string|int|float) foo, string|void separator)

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 capitalize

string String.capitalize(string str)

Description

Convert the first character in str to upper case, and return the new string.

See also

lower_case() , upper_case()


Method sillycaps

string String.sillycaps(string str)

Description

Convert the first character in each word (separated by spaces) in str to upper case, and return the new string.


Method common_prefix

string String.common_prefix(array(string) strs)

Description

Find the longest common prefix from an array of strings.


Method fuzzymatch

int(0..100) String.fuzzymatch(string a, string b)

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 soundex

string String.soundex(string word)

Description

Returns the soundex value of word according 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 int2roman

string String.int2roman(int m)

Description

Converts the provided integer to a roman integer (i.e. a string).

Throws

Throws an error if m is outside the range 0 to 10000.


Method int2size

string String.int2size(int size)

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.

Throws

Throws an error is size is less than zero.


Method expand_tabs

string String.expand_tabs(string s, int|void tab_width, string|void substitute_tab, string|void substitute_space, string|void substitute_newline)

Description

Expands tabs in a string to ordinary spaces, according to common tabulation rules.


Method int2char

string String.int2char(int x)

Description

Same as sprintf("%c",x);

See also

sprintf()


Method int2hex

string String.int2hex(int x)

Description

Same as sprintf("%x",x);, i.e. returns the integer x in hexadecimal base using lower cased symbols.

See also

sprintf()


Method string2hex

string String.string2hex(string data)

Description

Convert a string of binary data to a hexadecimal string.

See also

hex2string()


Method hex2string

string String.hex2string(string hex)

Description

Convert a string of hexadecimal digits to binary data.

See also

string2hex()


Method count

int String.count(string haystack, string needle)

Description

Count the number of non-overlapping times the string needle occurrs in the string haystack .

See also

search() , `/()


Method trim_whites

string String.trim_whites(string s)

Description

Trim leading and trailing spaces and tabs from the string s .


Method trim_all_whites

string String.trim_all_whites(string s)

Description

Trim leading and trailing white spaces characters (space, tab, newline and carriage return) from the string s .


Method width

int(8..8)|int(16..16)|int(32..32) String.width(string s)

Description

Returns the width of a string.

Three return values are possible:

8

The string s only contains characters <= 255.

16

The string s only contains characters <= 65535.

32

The string s contains characters >= 65536.


  CLASS String.Buffer

Description

A buffer, used for building strings. It's conceptually similar to a string, but you can only add strings to it, and you can only get the 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 create

void String.Buffer(int initial_size)

Description

Initializes a new buffer.

If no initial_size is specified, 256 is used. If you know approximately how big the buffer will be, you can optimize the operation of add() (slightly) by passing the size to this function.


Method _sprintf

string _sprintf(int flag, mapping flags)

Description

It is possible to sprintf a String.Buffer object as %s just as if it was a string.


Method cast

mixed cast(string type)

Description

It is possible to cast a String.Buffer object to a string and an int.


Method `+

String.Buffer `+(string what)


Method `+=

String.Buffer `+=(string what)


Method add

int add(string ... data)

Description

Adds data to the buffer. Returns the size of the buffer.


Method putchar

void putchar(int c)

Description

Appends the character c at the end of the string.


Method get_copy

string get_copy()

Description

Get the data from the buffer. Significantly slower than get , but does not clear the buffer.


Method get

string get()

Description

Get the data from the buffer.

Note

This will clear the data in the buffer


Method _sizeof

int _sizeof()

Description

Returns the size of the buffer.

  CLASS String.Replace


Method create

void String.Replace(array(string)|void from, array(string)|void to)


Method `()

string `()(string str)


Method _encode

array(string) _encode()


Method _decode

void _decode(array(array(string)) encoded)

  CLASS String.SingleReplace


Method create

void String.SingleReplace(string|void del, string|void to)


Method `()

string `()(string str)


Method _encode

array(string) _encode()


Method _decode

void _decode(array(string)|int(0..0) encoded)

  CLASS String.Bootstring

Description

This class implements the "Bootstring" string transcoder described in ftp://ftp.rfc-editor.org/in-notes/rfc3492.txt.


Method decode

string decode(string s)

Description

Decodes a Bootstring encoded string of "basic" code points back to the original string space.


Method encode

string encode(string s)

Description

Encodes a string using Bootstring encoding into a string constisting only of "basic" code points (< initial_n).


Method create

void String.Bootstring(int base, int tmin, int tmax, int skew, int damp, int initial_bias, int initial_n, int delim, string digits)

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.

  CLASS String.Iterator

Description

An object of this class is returned by get_iterator() when called with a string.

See also

get_iterator


Inherit predef::Iterator

inherit predef::Iterator : predef::Iterator

  CLASS String.SplitIterator

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 a SplitIterator.

foreach(str/"\n", string line) write("%s\n", line);


Inherit predef::Iterator

inherit predef::Iterator : predef::Iterator


Method create

void String.SplitIterator(string buffer, int|array(int)|multiset(int) split_set, int|void flags, function(:string)|void feed)

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 buffer is used up and the SplitIterator wants more data.

  Module String.Elite


Method elite_word

string String.Elite.elite_word(string in, void|int(0..100) leetp, void|int(0..2) eightbit)

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

string String.Elite.elite_string(string in, void|int(0..100) leetp, void|int(0..1) eightbit)

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 neccesary elite translations (picture -> pic, cool->kewl etc), then optional translations (ok->k, dude->dood, -ers -> -orz), then calls elite_word on the resulting words.

  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 select

string String.HTML.select(string name, array(string)|array(array(string)) choices, void|string selected)

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

string String.HTML.simple_obox(array(array(string)) rows, void|string frame_color, void|string cell_color, void|string width, void|string padding, void|function(int: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


Method pad_rows

array(array(string)) String.HTML.pad_rows(array(array(string)) rows, void|string padding)

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 "&nbsp;".

  CLASS String.HTML.OBox

Description

Provides the same functionality as the simple_obox function, 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 create

void String.HTML.OBox(void|string frame_color, void|string cell_color, void|string width, void|string padding, void|function(int:string) cell_callback)


Method set_cell_callback

void set_cell_callback(function(int:string) cell_callback)


Method set_extra_args

void set_extra_args(mapping(string:string) extra_args)

Description

The argument in the mapping will be added to all created table cells.


Method set_extra_args

void set_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.


Method add_raw_cell

void add_raw_cell(string cell)

Description

Adds this cell to the table unmodified, e.g. it should have an enclosing td or th element.


Method add_tagdata_cell

void add_tagdata_cell(string tag, mapping(string:string) args, string contents)

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 add_cell

void add_cell(string contents)

Description

Adds a cell with the provided content.


Method new_row

void new_row()

Description

Begin a new row. Succeeding cells will be added to this row instead of the current.


Method add_row

void add_row(array(string) cells)

Description

Adds a complete row. If the current row is nonempty a new row will be started.


Method pad_rows

void pad_rows()

Description

Ensures that all rows have the same number of cells.


Method render

string render()

Description

Returns the result.


Method cast

mixed cast(string to)

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.

  Module Array

Description

General functions to operate on arrays.


Method interleave_array

array(int) Array.interleave_array(array(mapping(int:mixed)) tab)

Description

Interleave a sparse matrix.

Returns an array with offsets that describe how to interleave the rows of tab .


Method longest_ordered_sequence

array(int) Array.longest_ordered_sequence(array a)

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 permute

array Array.permute(array in, int number)

Description

Give a specified permutation of an array.

The number of permutations is equal to sizeof(in )! (the factorial of the size of the given array).

See also

shuffle()


Method diff

array(array(array)) Array.diff(array a, array b)

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 array b .

See also

diff_compare_table() , diff_longest_sequence() , String.fuzzymatch()


Method diff_compare_table

array(array(int)) Array.diff_compare_table(array a, array b)

Description

Returns an array which maps from index in a to corresponding indices in b .

 > 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_longest_sequence

array(int) Array.diff_longest_sequence(array a, array b)

Description

Gives the longest sequence of indices in b that have corresponding values in the same order in a .

See also

diff() , diff_compare_table() , String.fuzzymatch()


Method diff_dyn_longest_sequence

array(int) Array.diff_dyn_longest_sequence(array a, array b)

Description

Gives the longest sequence of indices in b that have corresponding values in the same order in a .

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 uniq

array Array.uniq(array a)

Description

Remove elements that are duplicates.

Returns

This function returns an copy of the array a with 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

Elements are compared with `== . They are also hashed (see lfun::__hash for further details if the array contains objects).


Method splice

array(mixed) Array.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 everynth

array(mixed) Array.everynth(array(mixed) a, void|int n, void|int start)

Description

Return an array with every n :th element of the array a .

If n is zero every other element will be returned.

See also

splice() , `/()


Method transpose

array(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 reduce

mixed Array.reduce(function fun, array arr, mixed|void zero)

Description

reduce() sends the first two elements in arr to fun , then the result and the next element in arr to fun and so on. Then it returns the result. The function will return zero if arr is the empty array. If arr has only one element, that element will be returned.

See also

rreduce()


Method rreduce

mixed Array.rreduce(function fun, array arr, mixed|void zero)

Description

rreduce() sends the last two elements in arr to fun , then the third last element in arr and the result to fun and so on. Then it returns the result. The function will return zero if arr is the empty array. If arr has only one element, that element will be returned.

See also

reduce()


Method shuffle

array Array.shuffle(array arr)

Description

shuffle() gives back the same elements, but in random order. The array is modified destructively.

See also

permute()


Method search_array

int Array.search_array(array arr, string|function|int fun, mixed ... args)

Description

search_array() works like map() , 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 sum_arrays

array Array.sum_arrays(function(mixed ... :mixed) sum, array ... args)

Description

Applies the function sum columnwise on the elements in the provided arrays. E.g. sum_array(`+,a,b,c) does the same as `+(a[*],b[*],c[*]).


Method sort_array

array Array.sort_array(array arr, function|void cmp, mixed ... args)

Description

This function sorts the array arr after a compare-function cmp which takes two arguments and should return 1 if the first argument is larger then the second. Returns the sorted array - arr is not sorted destructively.

The remaining arguments args will be sent as 3rd, 4th etc. argument to cmp .

If cmp is omitted, `>() is used instead.

See also

map() , sort() , `>() , dwim_sort_func , lyskom_sort_func , oid_sort_func


Method columns

array(array) Array.columns(array x, array ind)

Description

Get multiple columns from an array.

This function is equvivalent to

   map(ind, lambda(mixed i) { return column(x, i); })
 

See also

column()


Method diff3

array(array(array)) Array.diff3(array a, array b, array c)

Description

Return the three-way difference between the arrays.

See also

Array.diff() , Array.diff_longest_sequence()


Method dwim_sort_func

int(-1..1) Array.dwim_sort_func(string a, string b)

Description

Sort without respect to number formatting (most notably leading zeroes).


Method lyskom_sort_func

int(-1..1) Array.lyskom_sort_func(string a, string b)

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 flatten

array Array.flatten(array a, mapping(array:array)|void state)

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 sum

mixed Array.sum(array a)

Description

Sum the elements of an array using `+. The empty array results in 0.


Method uniq2

array Array.uniq2(array a)

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 uniq function.


Method arrayify

array Array.arrayify(void|array|mixed x)

Description

Make an array of the argument, if it isn't already. A zero_type 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

zero_type(x)

arrayify(x) => ({})

otherwise

arrayify(x) => ({ x })


Method oid_sort_func

int Array.oid_sort_func(string a0, string b0)

Description

Sort with care of numerical sort for OID values: "1.2.1" before "1.11.1"

See also

sort_array


Method greedy_diff

array(array(array)) Array.greedy_diff(array from, array to)

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_diff optimizes the cases where Array.diff returns ({ ..., 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 count

int Array.count(array|mapping|multiset haystack, mixed needle)
mapping(mixed:int) Array.count(array|mapping|multiset haystack)

Description

Returns the number of occurrences of needle in haystack . If the optional needle argument is omitted, count instead works similar to the unix command sort|uniq -c, returning a mapping with the number of occurrences of each element in haystack . For array or mapping haystack s, it's the values that are counted, for multisets the indices, as you'd expect.

See also

String.count , search , has_value


Method common_prefix

array Array.common_prefix(array(array) arrs)

Description

Find the longest common prefix from an array of arrays.

See also

String.common_prefix


Method all

int(0..1) Array.all(array a, function(mixed:mixed) predicate, mixed ... extra_args)

Description

Returns 1 if all of the elements in a fulfills the requirement predicate ( 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

int(0..1) Array.any(array a, function(mixed:mixed) predicate, mixed ... extra_args)

Description

Returns 1 if any of the elements in a fulfills the requirement predicate ( 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 partition

array(array) Array.partition(array a, function(mixed:mixed) arbiter, mixed ... extra_args)

Description

Splits an array in two, according to an arbitration function arbiter . The elements in a who return non-zero for the expression arbiter ( 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 , `/ , `%

  CLASS Array.Iterator

Description

An object of this class is returned by get_iterator() when called with an array.

See also

get_iterator


Inherit predef::Iterator

inherit predef::Iterator : predef::Iterator

  Module Function


Method defined

string Function.defined(function fun)

Description

Returns a string with filename and linenumber where fun was defined.

Returns 0 (zero) when no line can be found, e.g. for builtin functions and functions in destructed objects.


Method splice_call

mixed Function.splice_call(array args, function f, mixed|void ... extra)

Description

Calls the given function with the args array plus the optional extra arguments as its arguments and returns the result.

Most useful in conjunction with map , and particularly in combination with sscanf with "...%{...%}..." scan strings (which indeed was what it was invented for in the first place).

Parameter args

The first arguments the function f expects.

Parameter f

The function to apply the arguments on.

Parameter extra

Optional extra arguments to send to f .

Returns

Whatever the supplied function f returns.

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 Y

function Function.Y(function 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; })


Method curry

function Function.curry(function 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 call_callback

void Function.call_callback(function 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.)

  Module Program


Method inherit_list

array(program) Program.inherit_list(program p)

Description

Returns an array with the programs that p has inherited.


Method all_inherits

array(program) Program.all_inherits(program p)

FIXME

Document this function.


Method inherit_tree

array Program.inherit_tree(program p)

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 implements

int Program.implements(program prog, program api)

Description

Returns 1 if prog implements api .


Method inherits

int Program.inherits(program child, program parent)

Description

Returns 1 if child has inherited parent .


Method defined

string Program.defined(program p)

Description

Returns a string with filename and linenumber describing where the program p was 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.

  Module ADT

Description

Various Abstract Data Types.


Inherit _ADT

inherit _ADT : _ADT

  CLASS ADT.CircularList

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 method allocate.


Method `[]

mixed `[](int 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 `[]=

mixed `[]=(int index, mixed value)

Description

Index assign operator. Set the value at the index index to be value

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 `+

CircularList `+(CircularList coll)

Description

Addition operator Append the content of this CircularList and coll and return the results as a new CircularList .

Parameter coll

The list to append to his list

Returns

The result of the append as a new CircularList .


Method _equal

int(0..1) _equal(mixed coll)

Returns

Returns true if the object coll is a CircularList and contains the same values in the same order.


Method _indices

array _indices()

Returns

The indices in this list as an array.


Method _insert_element

void _insert_element(int index, mixed value)

Description

Insert an element in the list at the position index , the value at the position index and all above will have thier index increased with 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.


Method _remove_element

mixed _remove_element(int index)

Description

Remove the values at index index from the list.

Parameter index

The index to remove.

Returns

The removed value.

Throws

An error if the index is out of range.


Method _search

int _search(mixed value, void|int 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 found UNDEFINED is 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.

Throws

An error if the start is out of range.


Method _sizeof

int _sizeof()

Returns

The number of elements in this list.


Method _values

array _values()

Returns

The values in this list as an array.


Method add

void add(mixed value)

Description

Add a value at the front of the list

Parameter value

The value to add.

Throws

An error if the list is full.


Method allocate

void allocate(int elements)

Description

Increase the maxsize of the CircularlList.

Parameter elements

Add this number of new elements to the list.


Method cast

mixed cast(string type)

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 clear

void clear()

Description

Clear the contents of the list.


Method delete_value

int delete_value(mixed value)

Description

Remove the first occurrence of the value value from 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 is_empty

int(0..1) is_empty()

Returns

Returns 1 if the list is empty otherwise 0.


Method max_size

int max_size()

Returns

Returns the maximal size of this list.


Method peek_back

mixed peek_back()

Returns

The value at the back of the list but do not remove it from the list.


Method peek_front

mixed peek_front()

Returns

The value at the front of the list but do not remove it from the list.


Method pop_back

mixed pop_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

mixed pop_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

void push_back(mixed value)

Description

Add a new value at the end of the list.

Parameter value

The value to add.


Method push_front

void push_front(mixed value)

Description

Add a new value at the end of the list.

Parameter value

The value to add.


Method create

void ADT.CircularList(array|int arg)

Description

Creates a new CircularList around the array arg or a new CircularList with the maximum size of arg.


Method _get_iterator

CircularListIterator _get_iterator(void|int ind)

Description

Create and initiate a new CircularListIterator that could be used to iterate over this list.

Parameter ind

If an ind value is supplied the iterator will be positioned at that index.

Returns

An iterator.


Method first

CircularListIterator first()

Description

Create and initiate a new CircularListIterator that could be used to iterate over this list.

Returns

An iterator positioned at the first element in the list.


Method last

CircularListIterator last()

Description

Create and initiate a new CircularListIterator that could be used to iterate over this list.

Returns

An iterator positioned after the last element in the list.

  CLASS ADT.CircularList.CircularListIterator

Description

This is the iterator for the CircularList. It implements the IndexIterator and the OutputIterator.


Method create

void ADT.CircularList.CircularListIterator(object list, void|int start)

Description

Creates a new iterator for the CircularList list . If start is supplied it will try to position the iterator at start .


Method index

int index()

Returns

The index at the current position.


Method value

mixed value()

Returns

The value at the current position.


Method `+

CircularListIterator `+(int steps)

Description

Move the iterator steps steps forward (negative value on steps will cause the iterator to move backwards) and return the result as a new iterator.

Returns

A new iterator positioned steps steps forward.


Method `+=

CircularListIterator `+=(int steps)

Description

Move this iterator steps steps forward (negative value on steps will cause the iterator to move backwards) and return the result.

Returns

This iterator positioned steps steps forward.


Method `-

CircularListIterator `-(int steps)

Description

Move the iterator steps steps backwards (negative value on steps will cause the iterator to move forwards) and return the result as a new iterator.

Returns

A new iterator positioned steps steps backwards.


Method has_next

int(0..1) has_next(void|int steps)

Returns

Returns true if it is possible to move steps steps forwards, if steps weren't supplied it check if it is possible to move one step forward.


Method has_previous

int(0..1) has_previous(void|int steps)

Returns

Returns true if it is possible to move steps steps backwards, if steps weren't supplied it check if it is possible to move one step backward.


Method `!

int(0..1) `!()

Returns

Returns false if the iterator has reached the end.


Method _equal

int(0..1) _equal(mixed iter)

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 `<

int(0..1) `<(mixed iter)

Description

Less then operator

Returns

Returns true if this iterator has a lower index then iter .


Method `>

int(0..1) `>(mixed iter)

Description

Greater then operator

Returns

Returns true if this iterator has a higher index then iter .


Method distance

int distance(object 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.


Method get_collection

CircularList get_collection()

Returns

Returns the CircularList this iterator currently iterates over.


Method set_value

mixed set_value(mixed val)

Description

Set the value at the current position.

Parameter val

The new value

Returns

Returns the old value

  CLASS ADT.Sequence

Description

The sequence work similar to an array but has the possibilities to insert and remove elements. It also has a more powerful iterator.


Method `[]

mixed `[](int 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 `[]=

mixed `[]=(int index, mixed value)

Description

Index assign operator. Set the value at the index index to be value .

Parameter index

The index to set.

Parameter value

The new value.

Returns

The new value at the index index .


Method `+

Sequence `+(Sequence coll)

Description

Addition operator Append the content of coll to thies sequence and return the results as a new Sequence .

Parameter coll

The sequence to append to his sequence.

Returns

The result of the append as a new Sequence .


Method `-

Sequence `-(Sequence coll)

Description

Subtraction operator Removes those values in this sequence that also are present in coll and return the results as a new Sequence .

Parameter coll

The sequence to subtract from this sequence.

Returns

The result of the subtraction as a new Sequence .


Method `&

Sequence `&(Sequence coll)

Description

And operator Perform an and on this sequence and the coll sequence by only returning those values that is present in both sequences as a new Sequence . 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 `|

Sequence `|(Sequence coll)

Description

Or operator Perform an or on this sequence and the coll sequence by returning those values that is present in both sequences as a new Sequence . 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 `^

Sequence `^(Sequence coll)

Description

Xor operator Perform a xor on this sequence and the coll sequence by returning those values that is present in one of the sequences but not in both adapters as a new Sequence . 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 _equal

int(0..1) _equal(mixed coll)

Returns

Returns true if the object coll is a Sequence and contains the same values in the same order.


Method _indices

array _indices()

Returns

The indices in this adapter as an array.


Method _insert_element

void _insert_element(int index, mixed value)

Description

Insert an element in the sequence at the position index , the value at the position index and all above will have their index increased with one.

Parameter index

The index to insert the value at.

Parameter value

The new value.


Method _remove_element

mixed _remove_element(int index)

Description

Remove the values at index index from the sequence.

Parameter index

The index to remove.

Returns

The removed value.


Method _search

int _search(mixed value, void|int start)

Description

Search the sequence for a specific value. Return the index of the first value that is equal to value . If no value was found UNDEFINED is 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 _sizeof

int _sizeof()

Returns

The number of elements in this adapter.


Method _values

array _values()

Returns

The values in this adapter as an array.


Method add

void add(mixed value)

Description

Add a value at the end of the sequence.

Parameter value

The value to add.


Method cast

mixed cast(string type)

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 clear

void clear()

Description

Clear the contents of the sequence.


Method delete_value

int delete_value(mixed value)

Description

Remove the first occurrence of the value value from 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 is_empty

int(0..1) is_empty()

Returns

Returns 1 if the sequence is empty otherwise 0.


Method max_size

int max_size()

Returns

Returns -1.


Method create

void ADT.Sequence(array|int arg)

Description

Creates a new Sequence around the array arg or a new Sequence with the size of arg.


Method _get_iterator

SequenceIterator _get_iterator(void|int ind)

Description

Create and initiate a new SequenceIterator that could be used to iterate over this sequence.

Parameter ind

If an ind value is supplied the iterator will be positioned at that index.

Returns

An iterator.


Method first

SequenceIterator first()

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

SequenceIterator last()

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 create

void ADT.Sequence.SequenceIterator(object sequence, void|int start)

Description

Creates a new iterator for the sequence sequence . If start is supplied it will try to position the iterator at start .


Method index

int index()

Returns

The index at the current position.


Method value

mixed value()

Returns

The value at the current position.


Method `+

SequenceIterator `+(int steps)

Description

Move the iterator steps steps forward (negative value on steps will cause the iterator to move backwards) and return the result as a new iterator.

Returns

A new iterator positioned steps steps forward.


Method `+=

SequenceIterator `+=(int steps)

Description

Move this iterator steps steps forward (negative value on steps will cause the iterator to move backwards) and return the result.

Returns

This iterator positioned steps steps forward.


Method `-

SequenceIterator `-(int steps)

Description

Move the iterator steps steps backwards (negative value on steps will cause the iterator to move forwards) and return the result as a new iterator.

Returns

A new iterator positioned steps steps backwards.


Method has_next

int(0..1) has_next(void|int steps)

Returns

Returns true if it is possible to move steps steps forwards, if steps weren't supplied it check if it is possible to move one step forward.


Method has_previous

int(0..1) has_previous(void|int steps)

Returns

Returns true if it is possible to move steps steps backwards, if steps weren't supplied it check if it is possible to move one step backward.


Method `!

int(0..1) `!()

Returns

Returns false if the iterator has reached the end.


Method _equal

int(0..1) _equal(mixed iter)

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 `<

int(0..1) `<(mixed iter)

Description

Less then operator.

Returns

Returns true if this iterator has a lower index then iter .


Method `>

int(0..1) `>(mixed iter)

Description

Greater then operator.

Returns

Returns true if this iterator has a higher index then iter .


Method distance

int distance(object 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.


Method get_collection

Sequence get_collection()

Returns

Returns the Sequence this iterator currently iterates over.


Method set_value

mixed set_value(mixed val)

Description

Set the value at the current position.

Parameter val

The new value.

Returns

Returns the old value.

  CLASS ADT.Heap


Method push

void push(mixed value)

FIXME

Document this function


Method adjust

void adjust(mixed value)

FIXME

Document this function


Method pop

mixed pop()

Description

Removes and returns the item on top of the heap, which also is the smallest value in the heap.


Method _sizeof

int _sizeof()

Description

Returns the number of elements in the heap.

  CLASS ADT.History

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.


Method create

void ADT.History(int max_size)

Description

max_size is the maximum number of entries that can reside in the history at the same time.


Method set_no_adjacent_duplicates

void set_no_adjacent_duplicates(int(0..1) i)

Description

Change how the History object should treat two identical values in a row. If 1 than only unique values are allowed after each other.

See also

query_no_adjacent_duplicates


Method query_no_adjacent_duplicates

int(0..1) query_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 push

void push(mixed value)

Description

Push a new value into the history.


Method _sizeof

int _sizeof()

Description

A sizeof operation on this object returns the number of elements currently in the history, e.g. <= the current max size.


Method get_maxsize

int get_maxsize()

Description

Returns the maximum number of values in the history

See also

set_maxsize


Method get_latest_entry_num

int get_latest_entry_num()

Description

Returns the absolute sequence number of the latest result inserted into the history.


Method get_first_entry_num

int get_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 `[]

mixed `[](int 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 `[]=

void `[]=(int i, mixed value)

Description

Overwrite one value in the history. The history position may be identified either by positive or negative offset, like `[] .


Method set_maxsize

void set_maxsize(int _maxsize)

Description

Set the maximume number of entries that can be stored in the history simultaneous.

See also

get_maxsize


Method flush

void flush()

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 _indices

array(int) _indices()

Description

Returns the index numbers of the history entries available.


Method _values

array _values()

Description

Returns the values of the available history entries.

  CLASS ADT.Priority_queue


Inherit Heap

inherit .Heap : Heap


Method push

mixed push(int pri, mixed val)

FIXME

Document this function


Method adjust_pri

void adjust_pri(mixed handle, int new_pri)

FIXME

Document this function


Method pop

mixed pop()

FIXME

Document this function

  CLASS ADT.Queue

Description

A simple FIFO queue.


Method create

void ADT.Queue(mixed ... args)

Description

Creates a queue with the initial items args in it.


Method write
Method put

void write(mixed item)
void put(mixed item)

Description

Adds the item to the queue.


Method read
Method get

mixed read()
mixed get()

Description

Returns the next element from the queue.


Method peek

mixed peek()

Description

Returns the next element from the queue without removing it from the queue.


Method is_empty

int(0..1) is_empty()

Description

Returns true if the queue is empty, otherwise zero.


Method flush

void flush()

Description

Empties the queue.


Method cast

mixed cast(string to)

Description

It is possible to cast ADT.Queue to an array.

  CLASS ADT.Stack

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.


Method push

void push(mixed val)

Description

Push an element on the top of the stack.


Method top

mixed top()

Description

Returns the top element from the stack, without popping it.

Throws

Throws an error if called on an empty stack.


Method quick_pop

void quick_pop(void|int val)

Description

Pops val entries from the stack, or one entry if no value is given. The popped entries are not actually freed, only the stack pointer is moved.


Method pop

mixed pop(void|int val)

Description

Pops and returns entry val from the stack, counting from the top. If no value is given the top element is popped and returned. All popped entries are freed from the stack.


Method reset

void reset(int|void initial_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 create

void ADT.Stack(int|void initial_size)

Description

An initial stack size can be given when a stack is cloned. The default value is 32.


Method set_stack

void set_stack(array stack)

Description

Sets the stacks content to the provided array.


Method _sizeof

int _sizeof()

Description

sizeof on a stack returns the number of entries in the stack.


Method _values

array _values()

Description

values on a stack returns all the entries in the stack, in order.


Method `+

this_program `+(this_program s)

Description

A stack added with another stack yields a third a third stack will all the stack elements from the two first stacks.

  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 ); }


Method create

void ADT.Struct(void|string|Stdio.File data)

Parameter data

Data to be decoded and populate the struct. Can either be a file object or a string.


Method decode

void decode(string|Stdio.File data)

Description

Decodes data according to the struct and populates the struct variables. The data can either be a file object or a string.


Method encode

string encode()

Description

Serializes the struct into a string. This string is equal to the string fed to decode if nothing in the struct has been altered.


Method `[]
Method `->

mixed `[](string item)
mixed `->(string item)

Description

The struct can be indexed by item name to get the associated value.


Method `[]=
Method `->=

mixed `[]=(string item)
mixed `->=(string item)

Description

It is possible to assign a new value to a struct item by indexing it by name and assign a value.


Method _indices

array(string) _indices()

Description

The indices of a struct is the name of the struct items.


Method _values

array _values()

Description

The values of a struct is the values of the struct items.


Method _sizeof

int _sizeof()

Description

The size of the struct object is the number of bytes allocated for the struct.


Method cast

mixed cast(string to)

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.

  CLASS ADT.Struct.Item

Description

Interface class for struct items.

  CLASS ADT.Struct.Byte

Description

One byte, integer value between 0 and 255.


Inherit Item

inherit Item : Item


Method create

void ADT.Struct.Byte(void|int(0..255) initial_value)

Description

The byte can be initialized with an optional value.

  CLASS ADT.Struct.Word

Description

One word (2 bytes) in network order, integer value between 0 and 65535.

See also

Drow


Inherit Item

inherit Item : Item


Method create

void ADT.Struct.Word(void|int(0..) initial_value)

Description

The byte can be initialized with an optional value.

  CLASS ADT.Struct.Drow

Description

One word (2 bytes) in intel order, integer value between 0 and 65535.

See also

Word


Inherit Word

inherit Word : Word

  CLASS ADT.Struct.Long

Description

One longword (4 bytes) in network order, integer value between 0 and 2^32.

See also

Gnol


Inherit Word

inherit Word : Word

  CLASS ADT.Struct.Gnol

Description

One longword (4 bytes) in intel order, integer value between 0 and 2^32.

See also

Long


Inherit Drow

inherit Drow : Drow

  CLASS ADT.Struct.Chars

Description

A string of bytes.


Inherit Item

inherit Item : Item


Method create

void ADT.Struct.Chars(int size, void|string value)

Description

The number of bytes that are part of this struct item. The initial value of the char string is value or, if not provided, a string of zero bytes.

  CLASS ADT.struct

Description

String buffer with the possibility to read and write data as they would be formatted in structs.


Method create

void ADT.struct(void|string s)

Description

Create a new buffer, optionally initialized with the value s .


Method contents

string contents()

Description

Trims the buffer to only contain the data after the read pointer and returns the contents of the buffer.


Method add_data

void add_data(string s)

Description

Adds the data s verbatim to the end of the buffer.


Method pop_data

string pop_data()

Description

Return all the data in the buffer and empties it.


Method put_uint

void put_uint(int i, int 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

void put_var_string(string s, int len_width)

Description

Appends a variable string s preceded with an unsigned integer of the size len_width declaring the length of the string. The string s should be 8 bits wide.


Method put_bignum

void put_bignum(Gmp.mpz i, int|void len_width)

Description

Appends a bignum i as a variable string preceded with an unsigned integer of the size len_width declaring the length of the string. len_width defaults to 2.


Method put_fix_string

void put_fix_string(string s)

Description

Appends the fix sized string s to the buffer.


Method put_fix_uint_array

void put_fix_uint_array(array(int) data, int item_size)

Description

Appends an array of unsigned integers of width item_size to the buffer.


Method put_var_uint_array

void put_var_uint_array(array(int) data, int item_size, int len)

Description

Appends an array of unsigned integers of width item_size to the buffer, preceded with an unsigned integer len declaring the size of the array.


Method get_uint

int(0..) get_uint(int len)

Description

Reads an unsigned integer from the buffer.


Method get_fix_string

string get_fix_string(int len)

Description

Reads a fixed sized string of length len from the buffer.


Method get_var_string

string get_var_string(int len)

Description

Reads a string written by put_var_string from the buffer.


Method get_bignum

Gmp.mpz get_bignum(int|void len)

Description

Reads a bignum written by put_bignum from the buffer.


Method get_rest

string get_rest()

Description

Get the remaining data from the buffer and clears the buffer.


Method get_fix_uint_array

array(int) get_fix_uint_array(int item_size, int size)

Description

Reads an array of integers as written by put_fix_uint_array from the buffer.


Method get_var_uint_array

array(int) get_var_uint_array(int item_size, int len)

Description

Reads an array of integers as written by put_var_uint_array from the buffer.


Method is_empty

int(0..1) is_empty()

Description

Returns one of there is any more data to read.

  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("À\0"0) > b->drain(); (3) Result: "À\0" > sizeof(b); (4) Result: 1


Method create

void ADT.BitBuffer(void|string _data)

Description

The buffer can be initialized with initial data during creation.


Method feed

this_program feed(string x)

Description

Adds full bytes to the buffer.


Method drain

string drain()

Description

Drains the buffer of all full (8-bits wide) bytes.


Method get

int get(int bits)

Description

Get bits from the buffer.

Throws

Throws an error in case of data underflow.


Method put

this_program put(int value, int bits)

Description

Put bits number of bits with the value value into the buffer.

Note

value must not be larger than what can be stored with the number of bits given in bits .


Method put0

this_program put0(int bits)

Description

Put bits number of 0 bits into the buffer.


Method put1

this_program put1(int bits)

Description

Put bits number of 1 bits into the buffer.


Method _sizeof

int _sizeof()

Description

sizeof() will return the number of bits in the buffer.

  Module ADT.Relation

  CLASS ADT.Relation.Binary


Method contains

mixed contains(mixed left, mixed right)

Description

Return true/false: does the relation "left R right " exist?


Method `()

mixed `()(mixed left, mixed right)

Description

Does the same as the contains function: returns true if the relation "left R right " exists, and otherwise false.


Method add

this_program add(mixed left, mixed right)

Description

Adds "left R right " as a member of the relation. Returns the same relation.


Method remove

this_program remove(mixed left, mixed right)

Description

Removes "left R right " as a member of the relation. Returns the same relation.


Method map

array map(function 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 f returns.


Method filter

object filter(function f)

Description

Filters the entries in the relation, and returns a relation with all those entries for which the filtering function f returned true. The function f gets two arguments: the left and the right value for every entry in the relation.


Method filter_destructively

this_program filter_destructively(function f)

Description

Filters the entries in the relation destructively, removing all entries for which the filtering function f returns false. The function f gets two arguments: the left and the right value for each entry in the relation.


Method _sizeof

mixed _sizeof()

Description

Returns the number of relation entries in the relation. (Or with other words: the number of relations in the relation set.)


Method `<=

mixed `<=(object rel)

Description

The expression `rel1 <= rel2' returns true if every relation entry in rel1 is also present in rel2.


Method `&

mixed `&(mixed rel)

Description

The expression `rel1 & rel2' returns a new relation which has those and only those relation entries that are present in both rel1 and rel2.


Method `+
Method `|

mixed `+(mixed rel)
mixed `|(mixed rel)

Description

The expression `rel1 | rel2' and `rel1 + rel2' returns a new relation which has all the relation entries present in rel1, or rel2, or both.


Method `-

mixed `-(mixed rel)

Description

The expression `rel1 - rel2' returns a new relation which has those and only those relation entries that are present in rel1 and not present in rel2.


Method make_symmetric

this_program 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.


Method find_shortest_path

array find_shortest_path(mixed from, mixed to, void|multiset avoiding)

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_path attempts 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 avoiding is either 0 (or omitted), or a multiset of nodes that must not be part of the path.


Method get_id

mixed get_id()

Description

Return the ID value which was given as first argument to create().

  CLASS ADT.Relation.Binary._get_iterator

Description

An iterator which makes all the left/right entities in the relation available as index/value pairs.

  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 encode

string encode()

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 decode

object decode(string s)

Description

This method returns a table object from a binary string representation of a table, as returned by encode() .


Method _indices

array(string) _indices()

Description

This method returns the column names for the table. The case used when the table was created will be returned.


Method _values

array(array) _values()

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 _sizeof

int _sizeof()

Description

This method returns the number of rows in the table.


Method reverse

object reverse()

Description

This method reverses the rows of the table and returns a new table object.


Method col

array col(int|string column)

Description

This method returns the contents of a given column as an array.


Method row

array row(int row_number)

Description

This method returns the contents of a given row as an array.


Method `[]

array `[](int|string column)

Description

Same as col() .


Method `==

int `==(object 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

object append_bottom(object table)

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

object append_right(object table)

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 select

object select(int|string ... columns)

Description

This method returns a new table object with the selected columns only.


Method remove

object remove(int|string ... columns)

Description

Like select() , but the given columns will not be in the resulting table.


Method where

object where(array(int|string)|int|string columns, function 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.


Method group

this_program group(mapping(int|string:function)|function f, mixed ... args)

Description

This method calls the function f for 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 sum

this_program sum(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 distinct

this_program distinct(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 map

object map(function f, array(int|string)|int|string columns, mixed ... args)

Description

This method calls the function f for 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 sort

object sort(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 rsort

object rsort(int|string ... columns)

Description

Like sort() , but in descending order.


Method limit

object limit(int n)

Description

This method truncates the table to the first n rows and returns a new object.


Method rename

object rename(string|int from, string to)

Description

This method renames the column named from to to and returns a new table object. Note that from can be the column position.


Method type

mapping type(int|string column, void|mapping type)

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 in create() .


Method create

void ADT.Table.table(array(array) table, array(string) column_names, array(mapping(string:string))|void column_types)

Description

The ADT.Table.table class 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_names will 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. If column_types is omitted, all columns will displayed as text.

See ADT.Table.ASCII.encode() on how to display a table.

See also

ADT.Table.ASCII.encode()

  Module ADT.Table.ASCII


Method encode

string ADT.Table.ASCII.encode(object table, void|mapping options)

Description

This method returns a table represented in ASCII suitable for human eyes. options is an optional mapping. If the keyword "indent" is used with a number, the table will be indented with that number of space characters.