5Built-in Class
5.1argument Class
5.1.1Overview
The argument class provides measures to access argument information that is passed to a function. One of its purposes is to check if an attribute is specified in the function call. It also provides a method to control a leader-trailer sequence, a mechanism that flow controls such as if-elsif-else and try-catch utilize.
There's no constructor to realize an instance of argument class. Its instance is implicitly created when a function is called, and you can refer to it by a variable named __arg__.
Below is an example to use argument class:
func(v0, v1, v2):[attr1,attr2] = {
printf('arg#%d %s\n', 0.., __arg__.values)
printf('attr1:%s attr2:%s\n', __arg__.isset(`attr1), __arg__.isset(`attr2))
}
5.1.2Property
An argument instance has the following properties:
argument#function … function [read-only]function instance that has created the argument.
argument#values … function [read-only]5.1.3Method
argument#finalize_trailer():voidargument#isset(symbol:symbol)true if the function is called with an attribute that matches the specified symbol.
argument#quit_trailer():voidCancels evaluation of following trailers.
Example:
f(flag:boolean) = {
!flag && __arg__.quit_trailer()
}
f(true) println('printed')
f(false) println('not printed')
5.2array Class
5.2.1Overview
An instance of the array class stores multiple numeric values in a seamless binary sequence. It can directly be passed to functions in C libraries without any modification that expect arrays of char, short, int, float, double and so on.
There are several array classes that deal with different element types as shown below:
| Class Name | Element Type |
|---|---|
array@int8 |
Int8 |
array@uint8 |
Uint8 |
array@int16 |
Int16 |
array@uint16 |
Uint16 |
array@int32 |
Int32 |
array@uint32 |
Uint32 |
array@int64 |
Int64 |
array@uint64 |
Uint64 |
array@half |
Half |
array@float |
Float |
array@double |
Double |
array@complex |
Complex |
In the specification described here, the class name is is represented as array@T where T means its element type.
Most of methods in array class are implemented in arrayt module while the class itself is provided by the intepreter. This is because array features cost much code size and it would be preferable to reduce the size of the intepreter body by separating the implementation of array methods. So, you have to import arrayt module before using the array class in your program.
5.2.2Property
An array instance has the following properties:
array#T … array [read-only]array#elembytes … number [read-only]array#elemtype … symbol [read-only]symbol including: `boolean, `int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64, `half, `float, `double and `complex.
array#major … symbol [read-only]`row or `column.
array#memoryid … string [read-only]array#ndim … number [read-only]array#p … pointer [read-only]array#shape … number [read-only]array#size … number [read-only]5.2.3Constructor
array(src?, elemtype?:symbol) {block?}
Creates an array instance that contains double type of elements from a list or an iterator specified as an argument src or from elements described in the block. The followings are examples to create an array instance:
array([[0, 1, 2], [3, 4, 5]])
array {{0, 1, 2}, {3, 4, 5}}
Specifying the argument elemtype would create an array of element type other than double. The following examples create an array instance of int32 elements:
array([[0, 1, 2], [3, 4, 5]], elemtype => `int32)
array(elemtype => `int32) {{0, 1, 2}, {3, 4, 5}}
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Functions named array@T where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32 ([[0, 1, 2], [3, 4, 5]])
array@int32 {{0, 1, 2}, {3, 4, 5}}
array.identity(n:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements that represents an identity matrix with specified size n.
Example:
x = array.identity(3)
// x is array@double {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of int32 elements:
array.identity(3, elemtype => `int32)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.identity where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.identity(3)
array.interval(begin:number, end:number, samples:number, elemtype?:symbol):static:map:[open,open_l,open_r] {block?}
Creates a one-dimentional array with double type of element that contains a sequence of numbers according to the beginning, ending numbers and the number of samples between them.
In default, it creates a sequence with a range of [begin, end] meaning that the sequence contains the beginning and ending numbers. Following attributes would control the range:
:open.. Numbers in range of(begin, end)that doesn't contain eitherbeginorend.:open_l.. Numbers in range of(begin, end]that doesn't containbegin.:open_r.. Numbers in range of[begin, end)that doesn't containend.
Example:
x = array.interval(0, 3, 7)
// x is array@double {0, 0.5, 1, 1.5, 2, 2.5, 3}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.interval(0, 3, 7, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.interval where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.interval(0, 3, 7)
array.ones(dims[]:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements, which are initialized with one. The argument dims specifies the dimension of the created array.
Example:
x = array.ones([3, 4])
// x is array@double {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of int32 elements:
array.ones([3, 4], elemtype => `int32)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.ones where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.ones([3, 4])
array.rands(dims[]:number, range?:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements which are initialized with random numbers. The argument dims specifies the dimension of the created array. When the argument range is specified, the generated elements are all integer numbers that are ranged within [0, range). Otherwise, the generated elements are real numbers ranged within [0, 1).
Example:
x = array.rands([3, 4], 10)
// x is like array@double {{6, 7, 6, 9}, {3, 3, 6, 0}, {7, 9, 5, 5}}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of int32 elements:
array.rands([3, 4], 10, elemtype => `int32)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rands where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.rands([3, 4], 10)
array.rands@normal(dims[]:number, mu?:number, sigma?:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements which are initialized with normal distribution random numbers. The argument dims specifies the dimension of the created array. The arguments mu and sigma supply parameters for normal distribution where mu specifies the mean value and sigma the standard deviation. In default, the mu is zero and sigma one.
Example:
x = array.rands@normal([3, 4], 1, 3)
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.rands@normal([3, 4], 1, 3, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rands@normal where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.rands@normal([3, 4], 1, 3)
array.range(num:number, num_end?:number, step?:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements that are initialized with a sequence of integer numbers.
This function can generate three types of sequence like below:
array.range(num).. between0and(num - 1).array.range(num, num_end).. betweennumand(num_end - 1).array.range(num, num_end, step).. betweennumand(num_end - 1)incremented bystep.
Example:
x = array.range(5)
// x is array@double {0, 1, 2, 3, 4}
x = array.range(2, 5)
// x is array@double {2, 3, 4}
x = array.range(2, 10, 2)
// x is array@double {2, 4, 6, 8}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of int32 elements:
array.range(5, elemtype => `int32)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.range where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.range(5)
array.rotation(angle:number, xtrans?:number, ytrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array of double type of elements representing a matrix to rotate a 2-D coord.
The rotation angle is specified in radian value. If the attribute :deg is specified, the angle is specified in degree value.
If one or both of xtrans and ytrans are specified, it would create an array that works as translation as well as rotation.
Example:
x = array.rotation(math.pi / 6)
// x is a matrix to rotate by pi/6.
x = array.rotation(30):deg
// x is a matrix to rotate by 30 degree, which is pi/6 in radian.
x = array.rotation(math.pi / 6, 3, 5)
// x is a matrix to rotate by pi/6 and translate by [3, 5].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.rotation(math.pi / 6, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rotation where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.rotation(math.pi / 6)
array.rotation@x(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array of double type of elements representing a matrix to rotate a 3-D coord around x-axis.
The rotation angle is specified in radian value. If the attribute :deg is specified, the angle is specified in degree value.
If one or more of xtrans, ytrans and ztrans are specified, it would create an array that works as translation as well as rotation.
Example:
x = array.rotation@x(math.pi / 6)
// x is a matrix to rotate by pi/6.
x = array.rotation@x(30):deg
// x is a matrix to rotate by 30 degree, which is pi/6 in radian.
x = array.rotation@x(math.pi / 6, 3, -2, 5)
// x is a matrix to rotate by pi/6 and translate by [3, -2, 5].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.rotation@x(math.pi / 6, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rotation@x where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.rotation@x(math.pi / 6)
array.rotation@y(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array of double type of elements representing a matrix to rotate a 3-D coord around y-axis.
The rotation angle is specified in radian value. If the attribute :deg is specified, the angle is specified in degree value.
If one or more of xtrans, ytrans and ztrans are specified, it would create an array that works as translation as well as rotation.
Example:
x = array.rotation@y(math.pi / 6)
// x is a matrix to rotate by pi/6.
x = array.rotation@y(30):deg
// x is a matrix to rotate by 30 degree, which is pi/6 in radian.
x = array.rotation@y(math.pi / 6, 3, -2, 5)
// x is a matrix to rotate by pi/6 and translate by [3, -2, 5].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.rotation@y(math.pi / 6, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rotation@y where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.rotation@y(math.pi / 6)
array.rotation@z(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array of double type of elements representing a matrix to rotate a 3-D coord around z-axis.
The rotation angle is specified in radian value. If the attribute :deg is specified, the angle is specified in degree value.
If one or more of xtrans, ytrans and ztrans are specified, it would create an array that works as translation as well as rotation.
Example:
x = array.rotation@z(math.pi / 6)
// x is a matrix to rotate by pi/6.
x = array.rotation@z(30):deg
// x is a matrix to rotate by 30 degree, which is pi/6 in radian.
x = array.rotation@z(math.pi / 6, 3, -2, 5)
// x is a matrix to rotate by pi/6 and translate by [3, -2, 5].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.rotation@z(math.pi / 6, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.rotation@z where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.rotation@z(math.pi / 6)
array.scaling(xscale:number, yscale:number, zscale?:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements representing a matrix to scale a coord.
It creates a matrix that works on a 2-D coord if xscale and yscale are specified while it creates a matrix on a 3-D coord if xscale, yscale and zscale are specified.
Example:
x = array.scaling(3, 4)
// x is a matrix to scale a 2-D coord by [3, 4].
x = array.scaling(3, 4, -2)
// x is a matrix to scale a 3-D coord by [3, 4, -2].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.scaling(3, 4, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.scaling where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.scaling(3, 4
array.translation(xtrans:number, ytrans:number, ztrans?:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements representing a matrix to translate a coord.
It creates a matrix that works on a 2-D coord if xtrans and ytrans are specified while it creates a matrix on a 3-D coord if xtrans, ytrans and ztrans are specified.
Example:
x = array.translation(3, 4)
// x is a matrix to translate a 2-D coord by [3, 4].
x = array.translation(3, 4, -2)
// x is a matrix to translate a 3-D coord by [3, 4, -2].
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of float elements:
array.translation(3, 4, elemtype => `float)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.translation where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@float.translation(3, 4
array.zeros(dims[]:number, elemtype?:symbol):static:map {block?}
Creates an array of double type of elements, which are initialized with zero. The argument dims specifies the dimension of the created array.
Example:
x = array.zeros([3, 4])
// x is array@double {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
Specifying the argument elemtype would create an array of element type other than double. The followings examples create an array instance of int32 elements:
array.zeros([3, 4], elemtype => `int32)
Available element types are:
`int8, `uint8, `int16, `uint16, `int32, `uint32, `int64, `uint64
`half, `float, `double, `complex
Methods named array@T.zeros where T gets an element type name are also provided to create an array instance of a specific type more easily. Using these functions could simplify the code above like this:
array@int32.zeros([3, 4])
5.2.4Method
array#argmax(axis?:number):map:[last_index] {block?}array.
array#argmin(axis?:number):map:[last_index] {block?}array.
array.dot(a:array, b:array):static:map {block?}Calculates a dot product between two arrays that have one or two dimensions.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#dump(stream?:stream):void:[upper]array#each():[flat] {block?}Creates an iterator that iterates each element in the array.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
The block parameter is |elem:number, idx:number| where elem is the element value.
array#elemcast(elemtype:symbol) {block?}Cast value type of contained elements.
Available symbols for elemtype are as follows:
`boolean`int8`uint8`int16`uint16`int32`uint32`int64`uint64`half`float`double`complex
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#fill(value:number):voidarray#flatten() {block?}
Returns an array instance as a result that has flattened elements in the target array.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#head(n:number):map {block?}
Returns an array instance as a result that has extracted n elements from the beginning of the target array.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#invert(eps?:number) {block?}array instance as a result that has elements of inverted matrix of the target array. If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#iselemsame(array:array)true if the target array instance has the same elements with the specified array.
array#issquare()true if the target array consists square matrices.
array#max(axis?:number):map:[index,last_index] {block?}array.
array#mean(axis?:number):map {block?}Calculates an mean value of elements in the array.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#min(axis?:number):map:[index,last_index] {block?}array.
array#offset(n:number):map {block?}
Returns an array instance as a result that has extracted elements of the target array after skipping its first n elements.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#paste(offset:number, src:array):map
Pastes elements of src into the target array instance.
The argument offset specifies the posision where elements are pasted in
array#reshape(dims[]:number:nil) {block?}
Returns an array instance as a result that has reshaped the target array according to a list of dimension size specified by dims.
Below are examples:
x = array(1..24)
a = x.reshape([6, 4]) // a is an array of 6x4.
b = x.reshape([2, 3, 4]) // b is an array of 2x3x4.
A value of nil in the list of dimension means it would be calculated from the whole size and other dimension sizes. Only one nil is allowed to exist.
x = array(1..24)
b = x.reshape([2, nil, 4]) // b is an array of 2x3x4.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#roundoff(threshold?:number) {block?}
Returns an array instance as a result that has rounded off elements less than threshold to zero in the target array. The default value for threshold is 1.0e-6 when omitted.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#std(axis?:number):map:[p] {block?}
Calculates a standard deviation value of elements in the target array.
In default, it calculates an unbiased estimation of standard deviation in which the summation of squared deviations is divided by (n - 1). Specifying :p attributes will calculate a population variance that divides that summation by n.
array#sum(axis?:number):map {block?}array.
array#tail(n:number):map {block?}
Returns an array instance as a result that has extracted n elements from the bottom of the target array.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#transpose(axes[]?:number) {block?}
Creates an array instance that transposes axes of the original array according to the specified argument axes.
If the argument is not specified, two axes at the lowest rank, which correspond to row and column for a matrix, would be transposed.
If block is specified, it would be evaluated with a block parameter |array:array|, where array is the created instance. In this case, the block's result would become the function's returned value.
array#var(axis?:number):map:[p] {block?}
Calculates a variation value of elements in the target array.
In default, it calculates an unbiased estimation of standard deviation in which the summation of squared deviations is divided by (n - 1). Specifying :p attributes will calculate a population variance that divides that summation by n.
5.3audio Class
5.3.1Overview
The audio class provides measures to work on audio data.
5.3.2Method
audio#each(channel:number, offset?:number):map {block?}audio#get(channel:number, offset:number):mapaudio#put(channel:number, offset:number, data:number):map:reduceaudio#sinewave(channel:number, freq:number, len:number, amplitude?:number):map:reduceaudio#store(channel:number, offset:number, data:iterator):reduce5.4binary Class
5.4.1Overview
The binary class provides measures to work on binary data that is a byte sequence without any format.
You can create a binary instance by calling binary() function.
You can also create the instance by specifying b prefix before a string literal. For example, the code below creates a binary instance that contains a sequence 0x41, 0x42, 0xfe, 0x03, 0x43, 0x44.
b'AB\xfe\x03CD'
5.4.2Property
A binary instance has the following properties:
binary#p … pointer [read-only]pointer instance that accesses the binary. This result is equivalent to that of calling the method binary#pointer()
binary#size … number [read-only]binary#writable … boolean [read-only]5.4.3Constructor
binary(buff*) {block?}
Creates a binary instance after combining string or binary specified by the arguments buff. If no argument is specified for buff, an empty binary instance would be created.
If block is specified, it would be evaluated with a block parameter |bin:binary|, where bin is the created instance. In this case, the block's result would become the function's returned value.
5.4.4Method
binary.alloc(bytes:number, data?:number):static:map {block?}
Creates a binary instance that has the specified size of buffer. If the argument data, which should have a number between 0 and 255, is specified, the buffer would be initialized with the value.
If block is specified, it would be evaluated with a block parameter |bin:binary|, where bin is the created instance. In this case, the block's result would become the function's returned value.
binary#dump(stream?:stream:w):void:[upper]
Prints a hexadecimal dump from the content of the binary to the standard output. If the argument stream is specified, the result would be output to the stream.
In default, hexadecimal digit are printed with lower-case characters. Specifying an attribute :upper would output them with upper-case characters instead.
Example:
>>> b'A quick brown fox jumps over the lazy dog.'.dump():upper
41 20 71 75 69 63 6B 20 62 72 6F 77 6E 20 66 6F A quick brown fo
78 20 6A 75 6D 70 73 20 6F 76 65 72 20 74 68 65 x jumps over the
20 6C 61 7A 79 20 64 6F 67 2E lazy dog.
binary#pointer(offset?:number):map {block?}
Returns a pointer instance that has an initial offset specified by the argument offset. If the argument is omitted, it would return a pointer instance that points to the top of the binary.
If block is specified, it would be evaluated with a block parameter |p:pointer|, where p is the created instance. In this case, the block's result would become the function's returned value.
binary#reader() {block?}stream instance with which you can read data from the binary by stream#read() method. If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
binary#writer() {block?}stream instance with which you can append data to the binary by stream#write() method. If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
5.5boolean Class
5.5.1Overview
The boolean class represents a boolean data type that is used in logical operations including NOT, AND, OR and XOR.
The boolean type provides two values: true and false. The other types of values can also be calculated in logical operations according to the following general rule:
- The
nilvalue is evaluated asfalsevalue. - Other values are evaluated as
true.
Note that the number 0 is treated as true in logical operations.
5.6codec Class
5.6.1Overview
The codec class has features to decoding/encoding character codes stored in string and binary. Following measures are provided:
- Decode .. Converts specific character codes stored in
binaryinto UTF-8 code and generagesstringcontaining the result. It can also delete a CR code (0x0d) before a LF code (0x0d) at each end of line so that lines in the result are joined with LF code. - Encode .. Converts UTF-8 character codes stored in
stringinto specific codes and generatesbinarycontaining the result. It can also add a CR code (0x0d) before a LF code (0x0a) at each end of line so that lines in the result are joined with CR-LF sequence.
You can utilize these functions using codec class's methods codec#decode() and codec#encode() as well as using stream class's method to read/write text by specifying codec instance when creating its instance.
The actual functions for encoding and decoding are provided by sub modules under codecs module. Each module provides following codecs:
codecs.basic..us-ascii,utf-8,utf-16,utf-16le,utf-16becodecs.iso8859..iso-8859-1,iso-8859-2,iso-8859-3,iso-8859-4,iso-8859-5,iso-8859-6,iso-8859-7,iso-8859-8,iso-8859-9,iso-8859-10,iso-8859-11,iso-8859-13,iso-8859-14,iso-8859-15,iso-8859-16codecs.korean..cp949,euc-krcodecs.chinese..cp936,gb2312,gbk,cp950,big5codecs.japanese..euc-jp,cp932,shift_jis,ms_kanji,jis,iso-2022-jp
Importing other codec modules would expand available codecs. You can call codecs.dir() to get a list of codec names currently available.
5.6.2Predefined Variable
| Variable | Type | Explanation |
|---|---|---|
codec.bom@utf8 |
binary |
BOM for UTF-8: b'\xef\xbb\xbf' |
codec.bom@utf16le |
binary |
BOM for UTF-16 little endian: b'\xff\xfe' |
codec.bom@utf16be |
binary |
BOM for UTF-16 big endian: b'\xfe\xff' |
codec.bom@utf32le |
binary |
BOM for UTF-32 little endian: b'\xff\xfe\x00\x00' |
codec.bom@utf32be |
binary |
BOM for UTF-32 big endian: b'\x00\x00\xfe\xff' |
5.6.3Constructor
codec(encoding:string) {block?}
Creates a codec instance of the specified encoding name. You can call codecs.dir() to get a list of available encoding names.
If block is specified, it would be evaluated with a block parameter |codec:codec|, where codec is the created instance. In this case, the block's result would become the function's returned value.
5.6.4Method
codec#addcr(flag?:boolean):reduce
The codec's encoder has a feature to add a CR code (0x0d) before a LF code (0x0a) so that the lines are joined with CR-LF codes in the encoded result. This method enables or disables the feature.
- To enable it, call the method with the argument
flagset totrueor without any argument. - To disable it, call the method with the argument
flagset tofalse.
codec#decode(buff:binary):mapbuff and returns the decoded result as string.
codec#delcr(flag?:boolean):reduce
The codec's decoder has a feature to delete a CR code (0x0d) before a LF code (0x0a) so that the lines are joined with LF code in the decoded result. This method enables or disables the feature.
- To enable it, call the method with the argument
flagset totrueor without any argument. - To disable it, call the method with the argument
flagset tofalse.
codec#encode(str:string):mapstr and returns the encoded result as binary.
5.6.5Cast Operation
A function that expects a codec instance in its argument can also take a value of string that is recognized as a codec name.
With the above casting feature, you can call a function f(codec:codec) that takes a codec instance in its argument as below:
f(codec('utf-16')).. The most explicit way.f('utf-16').. Implicit casting: fromstringtocodec.
5.7color Class
5.7.1Overview
An instance of the color class represents a color data that consists of red, green, blue and alpha elements.
You can create a color instance by calling color() function.
There are class variables as shown below:
5.7.2Predefined Variable
| Variable | Type | Explanation |
|---|---|---|
color.names |
string[] |
A list of color names that can be passed to color() function. |
color.zero |
color |
Color instance equivalent with color(0, 0, 0, 0) |
color.black |
color |
Color instance equivalent with color(0, 0, 0, 255) |
color.maroon |
color |
Color instance equivalent with color(128, 0, 0, 255) |
color.green |
color |
Color instance equivalent with color(0, 128, 0, 255) |
color.olive |
color |
Color instance equivalent with color(128, 128, 0, 255) |
color.navy |
color |
Color instance equivalent with color(0, 0, 128, 255) |
color.purple |
color |
Color instance equivalent with color(128, 0, 128, 255) |
color.teal |
color |
Color instance equivalent with color(0, 128, 128, 255) |
color.gray |
color |
Color instance equivalent with color(128, 128, 128, 255) |
color.silver |
color |
Color instance equivalent with color(192, 192, 192, 255) |
color.red |
color |
Color instance equivalent with color(255, 0, 0, 255) |
color.lime |
color |
Color instance equivalent with color(0, 255, 0, 255) |
color.yellow |
color |
Color instance equivalent with color(255, 255, 0, 255) |
color.blue |
color |
Color instance equivalent with color(0, 0, 255, 255) |
color.fuchsia |
color |
Color instance equivalent with color(255, 0, 255, 255) |
color.aqua |
color |
Color instance equivalent with color(0, 255, 255, 255) |
color.white |
color |
Color instance equivalent with color(255, 255, 255, 255) |
5.7.3Property
A color instance has the following properties:
color#a … number [read/write]color#b … number [read/write]color#g … number [read/write]color#r … number [read/write]5.7.4Cast Operation
A function that expects a color instance in its argument can also take a value of symbol, string and list as below:
symbol.. Recognized as a color name to look up the color table.string.. Recognized as a color name to look up the color table.list.. Expected to contain elements in a format[red, green, blue]or[red, green, blue, alpha].
With the above casting feature, you can call a function f(c:color) that takes a color instance in its argument as below:
f(color(`purple)).. The most explicit way.f(`purple).. Implicit casting: fromsymboltocolor.f('purple').. Implicit casting: fromstringtocolor.f([128, 0, 128]).. Implicit casting: fromlisttocolor.
5.7.5Constructor
color(args+):map {block?}
Creates a color instance.
If block is specified, it would be evaluated with a block parameter |c:color|, where c is the created instance. In this case, the block's result would become the function's returned value.
There are two forms to call this function as below:
color(name:string, a?:number).. Creates an instance from color name and an optional alpha element. Predefined variablecolor.namesis a list that contains available color names. A string in a format of'#rrggbb'that is used in HTML documents is also acceptable as a color name.color(r:number, g?:number, b?:number, a?:number).. Creates an instance from RGB elements and an optional alpha element.
5.7.6Method
color#getgray()
Calculates a gray scale from RGB elements in the color instance.
This is computed by a formula: gray = 0.299 * red + 0.587 * blue + 0.114 * blue.
color#html()'#rrggbb' that is used in HTML documents.
color#list():[alpha]
Returns a list of RGB elements in a form [r, g, b].
Specifying :alpha attribute would add the alpha element to the list.
5.8complex Class
5.8.1Overview
The complex class provides measures to calculate complex numbers.
You can create a complex instance by following ways:
- Calls
complex()function with a real and imaginary part of numbers. e.g.,complex(2, 3) - Calls
complex.polar()function with an absolute value and an argument in radius. e.g.,complex.polar(5, math.pi / 6) - Appending
jsuffix after a number literal would create an imaginal part of a complex numbrer. e.g.,2 + 3j
5.8.2Constructor
complex(real:number, imag?:number):map {block?}
Creates a complex instance with a real part real and an imaginary part imag.
If the argument imag is omitted, the imaginary part would be set to zero.
If block is specified, it would be evaluated with a block parameter |n:complex|, where n is the created instance. In this case, the block's result would become the function's returned value.
5.8.3Method
complex.polar(abs:number, arg:number):static:map:[deg] {block?}
Creates a complex instance with an absolute number abs and an angle arg in polar coords.
The argument arg is specified in a unit of radian. You can give it a degree value by calling the function with :deg attribute.
If block is specified, it would be evaluated with a block parameter |n:complex|, where n is the created instance. In this case, the block's result would become the function's returned value.
complex.roundoff(threshold:number => 1e-10) {block?}Returns a complex number with real and imaginary parts being rounded off.
The argument threshold specifies the threshold value for the round-off.
If block is specified, it would be evaluated with a block parameter |n:complex|, where n is the created instance. In this case, the block's result would become the function's returned value.
5.9datetime Class
5.9.1Overview
The datetime class provides measures to handle date and time information.
You can create a datetime instance by calling following functions:
datetime().. Creates an intance from specified date and time.datetime.now().. Creates an instance with its date and time fields set as the current one.datetime.today().. Creates an instance with its date field set as the current one. Its time fields,hour,min,secandusec, are set to zero.
You can calculate a datetime with a timedelta to put its date and time values forward and backward.
5.9.2Predefined Variable
| Variable | Type | Explanation |
|---|---|---|
datetime.Sunday |
number |
Assigned with number 0 that represents Sunday. |
datetime.Monday |
number |
Assigned with number 1 that represents Monday. |
datetime.Tuesday |
number |
Assigned with number 2 that represents Tuesday. |
datetime.Wednesday |
number |
Assigned with number 3 that represents Wednesday. |
datetime.Thursday |
number |
Assigned with number 4 that represents Thursday. |
datetime.Friday |
number |
Assigned with number 5 that represents Friday. |
datetime.Saturday |
number |
Assigned with number 6 that represents Saturday. |
5.9.3Property
A datetime instance has the following properties:
datetime#day … number [read/write]datetime#hour … number [read/write]datetime#min … number [read/write]datetime#month … number [read/write]datetime#sec … number [read/write]datetime#unixtime … number [read-only]datetime#usec … number [read/write]datetime#wday … number [read-only]datetime#week … number [read-only]datetime#yday … number [read-only]datetime#year … number [read/write]5.9.4Constructor
datetime(year:number, month:number, day:number, hour:number => 0, min:number => 0, sec:number => 0, usec:number => 0, minsoff?:number):map {block?}
Creates an instance of datetime class based on the specified arguments.
Explanations of the arguments are shown below:
year.. Christian year.month.. Month starting from 1. Numbers from 1 to 12 correspond to January to December.day.. Day in a month starting from 1.hour.. Hour in a day between 0 and 23.min.. Minute in an hour between 0 and 59.sec.. Second in a minute between 0 and 59.usec.. Millisecond in a second between 0 and 999.minsoff.. Timezone offset in minutes.
In default, the instance has a timezone offset based on the current system settings.
If block is specified, it would be evaluated with a block parameter |dt:datetime|, where dt is the created instance. In this case, the block's result would become the function's returned value.
5.9.5Method
datetime#clrtzoff():reducedatetime#format(format => `w3c)
Returns a string of the datetime properties based on the specified format. For the argument format, you can specify either a string of user-specific format or a symbol of predefined style.
A string of user-specific format contains following specifiers:
%d.. day of month%H.. hour in 24-hour format%I.. hour in 12-hour format%m.. month%M.. minute%S.. second%w.. week number starting from 0 for Sunday.%y.. lower two digits of year%Y.. four digits of year
Below are the symbols of predefined styles:
`w3c.. W3C style. eg)'2015-01-01T12:34:56+09:00'`http.. a style used in HTTP protocol. eg)'Thu, 01 Jan 2015 12:34:56 +0900'`asctime.. a style used by the C functionasctime(). eg)'Thu Jan 1 12:34:56 +0900 2015'
datetime.isleap(year:number):static:maptrue if the specified year is a leap one.
datetime.monthdays(year:number, month:number):static:map {block?}Returns a number of days that exists in the specified month.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
datetime.now():static:[utc] {block?}
Creates a datetime instance of the current time.
In default, the timezone offset is set to one in the system setting. Specifying :utc attribute would set the offset to 0.
If block is specified, it would be evaluated with a block parameter |dt:datetime|, where dt is the created instance. In this case, the block's result would become the function's returned value.
datetime.parse(str:string):static:map {block?}
Parses a string that describs date and time information and returns the datetime instance.
It is capable of parsing the following style:
- RFC1123 style. eg)
'Sat, 06 Nov 2010 08:49:37 GMT' - RFC1036 style. eg)
'Saturday, 06-Nov-10 08:49:37 GMT' - C's
asctime()style. eg)'Sat Nov 6 08:49:37 2010','Sat Nov 6 08:49:37 +0000 2010' - W3C style. eg)
'2010-11-06T08:49:37Z'
If block is specified, it would be evaluated with a block parameter |dt:datetime|, where dt is the created instance. In this case, the block's result would become the function's returned value.
datetime#settzoff(mins:number):reducedatetime.time(hour:number => 0, minute:number => 0, sec:number => 0, usec:number => 0):static:map {block?}
Creates a datetime instance from time information. The date inforomation is set as 1st of January in the Christian year of 0.
If block is specified, it would be evaluated with a block parameter |dt:datetime|, where dt is the created instance. In this case, the block's result would become the function's returned value.
datetime.today():static:[utc] {block?}
Creates a datetime instance of today. All the time information are cleared to 0.
In default, the timezone offset is set to one in the system setting. Specifying :utc attribute would set the offset to 0.
If block is specified, it would be evaluated with a block parameter |dt:datetime|, where dt is the created instance. In this case, the block's result would become the function's returned value.
datetime#utc()datetime instance. An error occurs if the instance has no timezone offset
datetime.weekday(year:number, month:number, day:number):static:map5.10declaration Class
5.10.1Overview
The declaration class provides information about argument's declaration defined in a function. You can get an iterator of declaration instances with the following measures that the function class provides:
- A property value:
function#decls - An instance method:
function.getdecls()
Below is an example to print argument names declared in a function.
f(a, b, c, d) = {}
println(f.decls:*name)
5.10.2Property
A declaration instance has the following properties:
declaration#default … number [read-only]expr instance that represents a default value in the declaration if exists. This is nil when no default value is specified.
declaration#name … number [read-only]string instance that represents the declaration's name.
declaration#symbol … number [read-only]symbol instance that represents the declaration's name.
5.10.3Method
declaration#istype(type+:expr):map
Return true if the declaration is defined as a type that is specified in the arguments.
The argument type has following formats:
- a single symbol.
- a sequence of symbols joined by a dot.
In the second format, a symbol on the left side indicates a container such as a module and a class.
Below is an example to check if the declaration is defined as number type.
decl.istype(`number)
Below is an example to check if the declaration is defined as re.match type, which is a type named match defined in re module.
decl.istype(`re.match)
You can also specify a type by describing factors in separate arguments like below:
decl.istype(`re, `match)
5.11dict Class
5.11.1Overview
The dict class provides measures to handle dictionary data that can seek values by indexing with their associated keys. You can specify values of string, number and symbol as a dictionary key.
You can create a dict instance by following measures:
- Calls
dict()constructor. - Calls a function named
%that is an alias ofdict()constructor.
Below are examples to create a dict instance:
dict {'first' => 1, 'second' => 2, 'third' => 3}
dict {{'first', 1}, {'second', 2}, {'third', 3}}
dict {'first', 1, 'second', 2, 'third', 3}
dict(['first' => 1, 'second' => 2, 'third' => 3])
dict([['first', 1], ['second', 2], ['third', 3]])
dict(['first', 1, 'second', 2, 'third', 3])
%{'first' => 1, 'second' => 2, 'third' => 3}
%{{'first', 1}, {'second', 2}, {'third', 3}}
%{'first', 1, 'second', 2, 'third', 3}
You can specify different type of values for keys in the same dictionary. In this case, values of different types are just recognized as different values.
5.11.2Index Access
You can read and write element values in a dict with an indexer by giving it a key value which type is string, number or symbol. Below is an example:
x = %{'first' => 1, 'second' => 2, 'third' => 3}
println(x['second']) // prints `2`
x['third'] = 33 // replaces `3` with `33`
5.11.3Constructor
dict(elems?):[icase] {block?}
Creates a dict instance.
It takes a list of key-value pairs in an argument as shown below:
d = dict([['apple', 100], ['grape', 200], ['banana', 80]])
Or, you can use a block to describe them like below:
d = dict {
['apple', 100], ['grape', 200], ['banana', 80]
}
You can specify values of number, string or symbol as dictionary keys.
You can also use the operator => to create a key-value pair like below:
d = dict(['apple' => 100, 'grape' => 200, 'banana' => 80])
Below is an example using a block:
d = dict {
'apple' => 100, 'grape' => 200, 'banana' => 80
}
The symbol % is an alias of the function dict().
d = %{
'apple' => 100, 'grape' => 200, 'banana' => 80
}
In default, if keys contain alphabet characters, different cases are distinguished. Appending the attribute :icase would ignore cases in them.
5.11.4Method
dict#append(elems?):reduce:[overwrite,strict,timid] {block?}
Adds multiple key-value pairs. It takes a list of key-value pairs in an argument or in a block that has the same format with one for the function dict().
If the specified key already exists in the dictionary, it would be overwritten. This behavior can be customized with the following attributes:
:overwrite.. overwrite the existing one (default):strict.. raises an error:timid.. keep the existing one
dict#clear()dict#erase(key):map
Erases a key-value pair that mathces the provided key.
The key is either number, string or symbol.
dict#get(key, default?):map:[raise]
Seeks a value that is associated with the specified key.
The method would return nil as its default value when the specified key doesn't exist in the dictionary. It would use different value if the argument default is specified.
Since the default value is also processed with implicit mapping, you have to apply object#nomap() method to it if you want to specify a list or an iterator as a default value.
When the attribute :raise is specified, an error occurs in the case of the key's absence.
Another measure to get a value associated with a key is to use an index operator. The following two codes have the same effect.
v = d['foo']v = d.get('foo'):raise
dict#haskey(key):maptrue if the specified key exists in the dictionary.
dict#items() {block?}Returns an iterator of key-value pairs in the dictionary.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
dict#keys() {block?}Returns an iterator of keys in the dictionary.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
dict#len()dict#put(key, value):map:reduce:[overwrite,strict,timid]Adds a new key-value pair.
If the specified key already exists in the dictionary, it would be overwritten. This behavior can be customized with the following attributes:
:overwrite.. overwrite the existing one (default):strict.. raises an error:timid.. keep the existing one
Another measure to add a key-value pair is to use an index operator. The following two codes have the same effect.
d['foo'] = 3d.put('foo', 3)
dict#values() {block?}Returns an iterator of values in the dictionary.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
5.12directory Class
5.12.1Overview
The directory class handles information necessary to seek directory structure in a path. Its instance usually works with functions in path module: path.dir() and path.walk().
Though the instance can be created by directory() function, you don't have to use it in many cases because a casting from string to directory instance works implicitly in a function call.
5.12.2Constructor
directory(pathname:string):map {block?}directory instance from the specified path name.
5.13environment Class
5.13.1Overview
The environment class provides measures to operate variables in an environment, which is a fundamental mechanism to store variables.
5.13.2Method
environment#getprop!(symbol:symbol):mapenvironment#lookup(symbol:symbol, escalate:boolean => true):mapenvironment#setprop!(symbol:symbol, value):map5.14error Class
5.14.1Overview
The error class provides measures to access error information.
There is no measures to create an error instance. They're instantiated and passed to a block of catch() function when an error occurs within a try block in a try-catch sequence.
In the following code, e is an instance that contains information about an error that has occured in the try block.
try {
// any jobs
} catch {|e:error|
// ...
}
5.14.2Predefined Variable
| Variable | Explanation |
|---|---|
error.ArgumentError |
Argument error. |
error.ArithmeticError |
Arithmetic error. |
error.AttributeError |
Invalid attribute is specified. |
error.CodecError |
An error that is related to codec process. |
error.CommandError |
An error that could happen in command line. |
error.DeclarationError |
An error in a function\'s declarations. |
error.FormatError |
|
error.IOError |
|
error.ImportError |
|
error.IndexError |
|
error.IteratorError |
|
error.KeyError |
|
error.MemberAccessError |
|
error.MemoryError |
|
error.NameError |
|
error.NotImplementedError |
An error that could occur when a called function has no implemented body but an entry. |
error.OutOfRange |
Index number is out of range. |
error.ResourceError |
Resource error. |
error.RuntimeError |
Runtime error. |
error.SyntaxError |
Syntax error. |
error.SystemError |
System error. |
error.TypeError |
Type error. |
error.ValueError |
Invalid value is specified. |
error.ZeroDivisionError |
Zero-division occured in division or modulo operations. |
5.14.3Property
An error instance has the following properties:
error#lineno … number [read-only]error#linenobtm … number [read-only]error#postext … string [read-only]error#source … string [read-only]error#text … string [read-only]:lineno is specified, it would contain a line number.
error#trace … iterator [read-only]expr instances that indicate stack trace.
5.15expr Class
5.15.1Overview
The expr class provides inromation about the language's syntax expression.
5.15.2Property
An expr instance has the following properties:
expr#attrfront … list [read-only]expr#attrs … list [read-only]expr#attrsopt … list [read-only]expr#block … expr [read-only]expr#blockparam … iterator [read-only]expr#body … string [read-only]expr#car … expr [read-only]expr#cdr … expr [read-only]expr#child … expr [read-only]expr#children … iterator [read-only]expr#left … expr [read-only]expr#lineno … number [read-only]expr#linenobtm … number [read-only]expr#operator … operator [read-only]expr#postext … string [read-only]expr#right … expr [read-only]expr#source … string [read-only]expr#suffix … symbol [read-only]expr#symbol … symbol [read-only]expr#trailer … expr [read-only]expr#typename … string [read-only]expr#typesym … symbol [read-only]expr#value … any [read-only]5.15.3Constructor
expr(src:stream:r):map {block?}
Parses a Gura script from the stream src and creates an expr instance.
If block is specified, it would be evaluated with a block parameter |expr:expr|, where expr is the created instance. In this case, the block's result would become the function's returned value.
5.15.4Method
expr#eval(env?:environment) {block?}
Evaluates the expr instance.
If the argument env is specified, that environment is used for evaluation. If omitted, the current scope is used.
expr.parse(script:string):static:map {block?}
Parses a Gura script in the string script and creates an expr instance.
If block is specified, it will be evaluated with block parameter in a format of |expr:expr| where expr is the created instance.
expr#textize(style?:symbol, indent?:string)
Composes a script text from a content of expr.
Argument style specifies the text style output, which takes the following symbols:
`crammed.. Puts all the text in one line and removes volatile spaces.`oneline.. Puts all the text in one line.`brief.. Omits content of blocks and long strings with "..".`fancy.. Prints in the most readable style. This is the default.
The argument indent specifies a string used for indentation. Its default is a sequence of four spaces.
expr#tofunction(`args*)
Converts the expr into a function.
If the expr is a block that has a block parameter, that would be used as an argument list of the created function. Otherwise, the argument args declares the argument list.
It would be an error if args is specified and a block parameter exists as well.
expr#unquote()expr instance that has removed quote operator from the original expr.
expr#write(dst:stream:w, style?:symbol, indent?:string)
Outputs a script that describes the expression to the specified stream.
Argument style specifies the text style output, which takes the following symbols:
`crammed.. Puts all the text in one line and removes volatile spaces.`oneline.. Puts all the text in one line.`brief.. Omits content of blocks and long strings with "..".`fancy.. Prints in the most readable style. This is the default.
The argument indent specifies a string used for indentation. Its default is a sequence of four spaces.
expr#isunary()true if expr is an expression of unary.
expr#isunaryop()true if expr is an expression of unaryop.
expr#isquote()true if expr is an expression of quote.
expr#isbinary()true if expr is an expression of binary.
expr#isbinaryop()true if expr is an expression of binaryop.
expr#isassign()true if expr is an expression of assign.
expr#ismember()true if expr is an expression of member.
expr#iscollector()true if expr is an expression of collector.
expr#isroot()true if expr is an expression of root.
expr#isblock()true if expr is an expression of block.
expr#islister()true if expr is an expression of lister.
expr#isiterer()true if expr is an expression of iterer.
expr#iscompound()true if expr is an expression of compound.
expr#isindexer()true if expr is an expression of indexer.
expr#iscaller()true if expr is an expression of caller.
expr#isvalue()true if expr is an expression of value.
expr#isidentifier()true if expr is an expression of identifier.
expr#issuffixed()true if expr is an expression of suffixed.
5.16formatter Class
5.16.1Overview
The formatter class provides information about a format specifier.
The function printf() has the following declaration:
printf('name: %s, age: %d\n', name, age)
The first argument is a string containing format specifiers like %s and %d that determine the manner on how the correspoding values name and age should be formatted. In the formatting mechanism, when the specifiers %s and %d appear, it would call methods name.__format_s__() and age.__format_s__() respectively which are format handlers responsible of formatting these values. In general, a format handler has a format like __format_X__(fmt:formatter) where X is the symbol of the specifier and fmt is a formatter instance that carries information about the associated specifier such as minimum width and a padding character. The handler must return a string as its result.
The table below summarizes associations between specifiers and the method name of their format handlers:
| Specifier | Method Name |
|---|---|
%d |
__format_d__ |
%u |
__format_u__ |
%b |
__format_b__ |
%o |
__format_o__ |
%x |
__format_x__ |
%e |
__format_e__ |
%f |
__format_f__ |
%g |
__format_g__ |
%s |
__format_s__ |
%c |
__format_c__ |
This feature is supposed to be used when you want your original class's instance properly formatted in printf. Below is an example to implement a format handler for the specifier %d:
A = class {
// any implementations
__format_d__(fmt:format) = {
// returns a string for %d specifier.
}
}
a = A()
printf('%d', a) // a.__format_d__() is called
5.16.2Method
formatter#getminwidth()Returns an expected minimum width for the field.
For example, with '%3d', this method would return 3.
formatter#getpadding()
Returns a string containing a padding character, a space or '0'.
In default, a space is used for padding. For example, with '%3d', this method would return ' '.
When a character '0' appears after '%', that becomes the padding character. For example, with '%03d', this method would return '0'.
formatter#getplusmode()Returns a symbol that indicates an expected action when a positive number appears.
`none.. No character ahead of the number.`space.. A space should be inserted.`plus.. A plus character should be inserted.
formatter#getprecision()Returns an expected precision for the field.
For example, with '%.3d', this method would return 3.
formatter#isleftalign()
Returns true if the field is expected to be aligned on left.
For example, with '%-3d', this method would return true.
formatter#issharp()
Returns true if the specifier sequence includes '#' flag, which means some literal prefixes such as 0x are expected to be appended at the top.
For example, with '%#x', this method would return true.
formatter#isuppercase()
Returns true if alphabet characters are expected to be shown in upper case.
Upper case characters are requested when a specifier such as '%X', '%E' and '%G' is specified.
5.17function Class
5.17.1Overview
The function class provides measure to inspect information about the instance.
All the functions are instances of function class, so an implementation of a function means a realization of a function instance. You can also create the instance using function() constructor. The following two codes have the same result:
f(a:number, b:number, c:number) = {
(a + b + c) / 3
}
f = function(a:number, b:number, c:number) {
(a + b + c) / 3
}
Using function(), you can use variables prefixed by a dollar character so that they are automatically added to the argument list. In such a case, the variables are added to the argument list in the same order as they appear in the function body. The code below creates a function with a declaration f($a, $b, $c).
f = function {
($a + $b + $c) / 3
}
You can use & as an alias of function() as shown below:
f = &{
($a + $b + $c) / 3
}
5.17.2Property
A function instance has the following properties:
function#decls … iterator [read-only]declaration instances that provide information about argument declaration the function defines.
function#expr … expr [read/write]function#format … string [read-only]function#fullname … string [read-only]function#name … string [read/write]string instance that represents the function's name.
function#symbol … symbol [read/write]symbol instance that represents the function's name.
5.17.3Operator
You can print a function's help from the interactive prompt using the unary operator "~". Below is an example to print the help of printf() function:
>>> ~printf
5.17.4Constructor
function(`args*) {block}
Creates a function instance with an argument list of args and a procedure body provided by block.
Following two codes have the same effect with each other.
f = function(a, b, c) { /* any job */ }f(a, b, c) = { /* any job */ }
5.17.5Method
function.getdecls(func:function):static:map
Creates an iterator of declaration instances that provide information about argument declaration that the function instance func defines.
This class method returns the same information as the property function#decls.
function.getexpr(func:function):static:map
Returns an expression of the function instance func.
It would return nil if the function is implemented with binary programs, not scripts.
This class method returns the same information as the property function#expr.
function.getformat(func:function):static:map
Returns a string showing a declared format of the function instance func.
This class method returns the same information as the property function#format.
function.getfullname(func:function):static:map
Returns a full name of the function instance func, which is prefixed by a name of the module or the class the instance belongs to.
This class method returns the same information as the property function#fullname.
function.getname(func:function):static:map
Returns a name of the function instance func in string type.
This class method returns the same information as the property function#name.
function.getsymbol(func:function):static:map
Returns a name of the function instance func in symbol type.
This class method returns the same information as the property function#symbol.
function#mathdiff(var?:symbol):reduce
Returns a function instance that computes derivation of the target function, which is expected to contain only mathematical procedures. An error occurs if the target function has any elements that have nothing to do with mathematics.
In default, it differentiates the target function with respect to its first argument. Below is an example:
>>> f(x) = math.sin(x)
>>> g = f.mathdiff() // g is a function to compute math.cos(x)
Specify a symbol to argument var when you want to differentiate with respect to another variable.
You can check the result of derivation by seeing property function#expr like below:
>>> g.expr
`math.cos(x)
5.18gear@averagepool1d Class
5.18.1Overview
5.18.2Constructor
gear@averagepool1d(size:number, strides?:number, padding?:symbol, channel_pos?:symbol):map {block?}
Creates a gear@averagepool1d instance.
The size is a gear size.
The strides is a strides of sliding window. Default is one.
The padding is a padding style `valid or `same. Default is `same.
The channel_pos specifies where channel dimension is positioned and takes `first or `last. Default is `last.
5.18.3Property
A gear@averagepool1d instance has the following properties:
gear@averagepool1d#channel_pos … symbol [read-only]gear@averagepool1d#padding … symbol [read-only]gear@averagepool1d#size … number [read-only]gear@averagepool1d#strides … number [read-only]5.19gear@averagepool2d Class
5.19.1Overview
5.19.2Constructor
gear@averagepool2d(size[]:number, strides[]?:number, padding?:symbol, channel_pos?:symbol):map {block?}gear@averagepool2d instance.
5.19.3Property
A gear@averagepool2d instance has the following properties:
gear@averagepool2d#channel_pos … symbol [read-only]gear@averagepool2d#padding … symbol [read-only]gear@averagepool2d#size … number [read-only]gear@averagepool2d#strides … number [read-only]5.20gear@averagepool3d Class
5.20.1Overview
5.20.2Constructor
gear@averagepool3d(size[]:number, strides[]?:number, padding?:symbol, format?:symbol):map {block?}gear@averagepool3d instance.
5.20.3Property
A gear@averagepool3d instance has the following properties:
5.21gear@conv1d Class
5.21.1Overview
5.21.2Constructor
gear@conv1d(array:array, strides?:number, padding?:symbol, channel_pos?:symbol):map {block?}
Creates a gear@conv1d instance.
The array is an array instance that has one of the following shapes:
[size].. 1-dimension[size, channel_num].. 2-dimensions andchannel_posis`last[channel_num, size].. 2-dimensions andchannel_posis`first[filter_num, size].. 2-dimensions andchannel_posis`none[filter_num, size, channel_num].. 3-dimensions andchannel_posis`last[filter_num, channel_num, size].. 3-dimensions andchannel_posis`first
where size is the size of the filter's kernel, channel_num is the number of channels and filter_num is the number of filters.
The strides is a strides for a sliding window. Default is one.
The padding is a padding style and takes `valid or `same. Default is `same. When valid is specified, there is no padding. When same is specified, zero values are padded so that the result array has the size of the division of the original size by strides.
The channel_pos is a channel position and takes `none, `first or `last. If not specified, `none` for an array without channel dimensionand `last for others are to be set.
5.21.3Property
A gear@conv1d instance has the following properties:
gear@conv1d#array … array [read-only]gear@conv1d#channel_num … number [read-only]gear@conv1d#channel_pos … symbol [read-only]gear@conv1d#filter_num … number [read-only]gear@conv1d#padding … symbol [read-only]gear@conv1d#size … number [read-only]gear@conv1d#strides … number [read-only]5.22gear@conv2d Class
5.22.1Overview
5.22.2Constructor
gear@conv2d(array:array, strides[]?:number, padding?:symbol, channel_pos?:symbol):map {block?}
Creates a gear@conv2d instance.
The given array instance shoud have one of the following shapes:
[row_size, col_size].. 2-dimensions[row_size, col_size, channel_num].. 3-dimensions andchannel_posis`last[channel_num, row_size, col_size].. 3-dimensions andchannel_posis`first[filter_num, row_size, col_size].. 3-dimensions andchannel_posis`none[filter_num, row_size, col_size, channel_num].. 4-dimensions andchannel_posis`last[filter_num, channel_num, row_size, col_size].. 4-dimensions andchannel_posis`first
where row_size and col_size are the size of the filter's kernel, channel_num is the number of channels and filter_num is the number of filters.
The strides is a list of strides for a sliding window in row and column. Default is [1, 1].
The padding is a padding style and takes `valid or `same. Default is `same. When valid is specified, there is no padding. When same is specified, zero values are padded so that the result array has the size of the division of the original size by strides.
The channel_pos is a channel position and takes `none, `first or `last. If not specified, `none` for an array without channel dimensionand `last for others are to be set.
5.22.3Property
A gear@conv2d instance has the following properties:
gear@conv2d#array … array [read-only]gear@conv2d#channel_num … number [read-only]gear@conv2d#channel_pos … symbol [read-only]gear@conv2d#filter_num … number [read-only]gear@conv2d#padding … symbol [read-only]gear@conv2d#size … number [read-only]gear@conv2d#strides … number [read-only]5.23gear@conv3d Class
5.23.1Overview
5.23.2Constructor
gear@conv3d(array:array, strides[]?:number, padding?:symbol, channel_pos?:symbol):map {block?}
Creates a gear@conv3d instance.
The given array instance shoud have one of the following shapes:
[plane_size, row_size, col_size].. 3-dimensions[plane_size, row_size, col_size, channel_num].. 4-dimensions andchannel_posis`last[channel_num, plane_size, row_size, col_size].. 4-dimensions andchannel_posis`first[filter_num, plane_size, row_size, col_size].. 4-dimensions andchannel_posis`none[filter_num, plane_size, row_size, col_size, channel_num].. 5-dimensions andchannel_posis`last[filter_num, channel_num, plane_size, row_size, col_size].. 5-dimensions andchannel_posis`first
where plane_size, row_size and col_size are the size of the filter's kernel, channel_num is the number of channels and filter_num is the number of filters.
The strides is a list of strides for a sliding window in plane, row and column. Default is [1, 1, 1].
The padding is a padding style and takes `valid or `same. Default is `same. When valid is specified, there is no padding. When same is specified, zero values are padded so that the result array has the size of the division of the original size by strides.
The channel_pos is a channel position and takes `none, `first or `last. If not specified, `none` for an array without channel dimensionand `last for others are to be set.
5.23.3Property
A gear@conv3d instance has the following properties:
gear@conv3d#array … array [read-only]gear@conv3d#channel_num … number [read-only]gear@conv3d#channel_pos … symbol [read-only]gear@conv3d#filter_num … number [read-only]gear@conv3d#padding … symbol [read-only]gear@conv3d#size … number [read-only]gear@conv3d#strides … number [read-only]5.24gear@maxpool1d Class
5.24.1Overview
5.24.2Constructor
gear@maxpool1d(size:number, strides?:number, padding?:symbol, channel_pos?:symbol):map {block?}
Creates a gear@maxpool1d instance.
The size is a gear size.
The strides is a strides of sliding window. Default is one.
The padding is a padding style `valid or `same. Default is `same.
The channel_pos specifies where channel dimension is positioned and takes `first or `last. Default is `last.
5.24.3Property
A gear@maxpool1d instance has the following properties:
gear@maxpool1d#channel_pos … symbol [read-only]gear@maxpool1d#padding … symbol [read-only]gear@maxpool1d#size … number [read-only]gear@maxpool1d#strides … number [read-only]5.25gear@maxpool2d Class
5.25.1Overview
5.25.2Constructor
gear@maxpool2d(size[]:number, strides[]?:number, padding?:symbol, channel_pos?:symbol):map {block?}gear@maxpool2d instance.
5.25.3Property
A gear@maxpool2d instance has the following properties:
gear@maxpool2d#channel_pos … symbol [read-only]gear@maxpool2d#padding … symbol [read-only]gear@maxpool2d#size … number [read-only]gear@maxpool2d#strides … number [read-only]5.26gear@maxpool3d Class
5.26.1Overview
5.26.2Constructor
gear@maxpool3d(size[]:number, strides[]?:number, padding?:symbol, format?:symbol):map {block?}gear@maxpool3d instance.
5.26.3Property
A gear@maxpool3d instance has the following properties:
5.27gear@relu Class
5.27.1Overview
5.27.2Constructor
gear@relu() {block?}gear@relu instance.
5.28gear@sigmoid Class
5.28.1Overview
5.28.2Constructor
gear@sigmoid() {block?}gear@sigmoid instance.
5.29gear@softmax Class
5.29.1Overview
5.29.2Constructor
gear@softmax(axis?:number):map {block?}gear@softmax instance.
5.29.3Property
A gear@softmax instance has the following properties:
gear@softmax#axis … number [read-only]5.30gear@tanh Class
5.30.1Overview
5.30.2Constructor
gear@tanh() {block?}gear@tanh instance.
5.31help Class
5.31.1Overview
The help class provides measures to access help information associated with a function instance.
You can get a help instance from a function instance or a class by calling help@function() or help@class() respectively.
5.31.2Property
A help instance has the following properties:
help#doc … string [read-only]help#format … string [read-only]'markdown'.
help#lang … symbol [read-only]`en for English and `ja for Japanese.
help#title … string [read-only]5.31.3Method
help.text@iterator(lang:symbol):static {block?}Returns a help text for functions that return an iterator.
The argument lang is a symbol that specifies the language in which the text is written, e.g. `en for English and `ja for Japanese.
If block is specified, it would be evaluated with a block parameter |str:string|, where str is the created instance. In this case, the block's result would become the function's returned value.
help.text@block(lang:symbol, varname:string, typename:string):static {block?}Returns a help text that for functions that take a block .
The argument lang is a symbol that specifies the language in which the text is written, e.g. `en for English and `ja for Japanese.
In the text, variable names would be replaced by varname and type names by typename.
If block is specified, it would be evaluated with a block parameter |str:string|, where str is the created instance. In this case, the block's result would become the function's returned value.
help.presenter(format:string):static:void {block}
Registers a presentation procedure with a name specified by the argument format.
The procedure is written in the block that takes block parameters: |help:help|.
5.32image Class
5.32.1Overview
The image class provides following measures to handle graphic image data:
- Reads image data from a file.
- Writes image data to a file.
- Apply some modifications on image data including rotation, resize and color conversion.
Acceptable image data formats can be extended by importing modules. Below is a table to show image formats and name of modules that handle them. The string listed in "imagetype" column shows a name that is used by functions image(), image#read() and image#write() to explicitly specify the image data format in a process of reading and writing files.
| Image Format | Module Name | imagetype |
|---|---|---|
| BMP |
bmp |
'bmp' |
| GIF |
gif |
'gif' |
| JPEG |
jpeg |
'jpeg' |
| Microsoft Icon |
msico |
'msico' |
| PNG |
png |
'png' |
| PPM |
ppm |
'ppm' |
| TIFF |
tiff |
'tiff' |
5.32.2Property
An image instance has the following properties:
image#format … symbol [read-only]Takes one of the following symbols indicating what elements are stored in the memory:
`rgb.. red, green and blue`rgba.. red, green, blue and alpha
image#height … number [read-only]image#palette … palette [read/write]palette instance associated with this image. If there's no palette associated, this property returns nil.
image#width … number [read-only]5.32.3Constructor
image(args+):map {block?}Returns an image instance with specified characteristics. There are three forms to call the function as below:
image(format:symbol).. Creates an image instance of the specified format without buffer allocated.image(format:symbol, width:number, height:number, color?:color).. Allocates an image buffer with the specified size and fills it with the color.image(stream:stream, format?:symbol, imagetype?:string).. Reads image data from the stream and allocates necessary buffer in which the read data is stored.
The argument format specifies what elements are stored in the memory and takes one of the following symbols:
`rgb.. red, green and blue`rgba.. red, green, blue and alpha
In the third form, the format of the image data is determined by the byte sequence of the stream data and its file name.
You can also explicitly specify the image data format by the argument imagetype.
5.32.4Method
image#allocbuff(width:number, height:number, color?:color):reduce
Allocates a specified size of buffer in the image instance that is supposed to has no buffer allocated.
The allocated buffer will be filled with color. If omitted, it will be filled with zero value.
An error occurs in following cases:
- It fails to allocate necessary buffer.
- The
imageinstance already has allocated buffer.
image#blur(radius:number, sigma?:number) {block?}Returns a new image that blurs the original image with the given parameters.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#clear():reduce
Fills the buffer in the image instance with zero value.
This has the same effect with calling image#fill() with color.zero.
This method returns the reference to the target instance itself.
image#crop(x:number, y:number, width?:number, height?:number):map {block?}Returns a new image instance of the extracted area of the source image.
The extracted area is specified by the following arguments:
x.. The left position.y.. The top position.width.. The width. If it's omitted or specified withnil, the whole area on the right ofxwill be extracted.height.. The height. If it's omitted or specified withnil, the whole area on the bottom ofywill be extracted.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#delpalette():reduce
Deletes a palette instance that belongs to the image.
This method returns the reference to the target instance itself.
image#extract(x:number, y:number, width:number, height:number, element:symbol, dst):reduce
Extracts the element values within the specified area of the image, and store them into a list. The argument x and y specifies the left-top position, and width, and height does the size of the area.
The argument element takes the following symbol that specifies which element should be extracted:
`r.. red`g.. green`b.. blue`a.. alpha
The argument dst specifies the variable into which the extracted data is stored, which must be a list that has enough space to store the data.
This method returns the reference to the target instance itself.
image#fill(color:color):reduceFills the whole image with the specified color.
This method returns the reference to the target instance itself.
image#fillrect(x:number, y:number, width:number, height:number, color:color):map:reduce
Fills the specified area with the specified color. The argument x and y specifies the left-top position, and width, and height does the size of the area.
This method returns the reference to the target instance itself.
image#flip(orient:symbol):map {block?}
Returns a new image instance that flips the source image horizontally or vertically. You can specify the following symbol to the orient argument.
`horz.. flips horizontally.`vert.. flips vertically.`both.. flips both horizontally and vertically. This has the same effect with rotating the image 180 degrees.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#getpixel(x:number, y:number):map {block?}Returns a color of a pixel data at the specified position.
If block is specified, it would be evaluated with a block parameter |c:color|, where c is the created instance. In this case, the block's result would become the function's returned value.
image#grayscale() {block?}Returns a new image instance that converts the source image into gray scale.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#mapcolorlevel(map@r:array@uint8, map@g?:array@uint8, map@b?:array@uint8) {block?}Returns a new image that converts color levels according to the given table.
Each of the arguments map@r, map@g and map@b is an instance of array@uchar containing 256 numbers that range between 0 and 255 and corresponds to elements red, green and blue respectively. An element value in the source image becomes an index of the list and the indexed value will be stored as a converted element value.
If you want to apply a mapping table to all the elements, call the method with a single argument like image#mapcolorlevel(map).
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#paste(x:number, y:number, src:image, width?:number, height?:number, xoffset:number => 0, yoffset:number => 0, a:number => 255):map:reduce
Pastes the source image src onto the target image instance at the specified position.
The argument width, height, xoffset and yoffset specify the source image's area to be pasted. If they're omitted, the whole image will be pasted.
The argument a specifies the alpha value that is put on the target image.
This method returns the reference to the target instance itself.
image#putpixel(x:number, y:number, color:color):map:reducePuts a color on the specified position.
This method returns the reference to the target instance itself.
image#size()[width, height].
image#store(x:number, y:number, width:number, height:number, element:symbol, src):reduceimage#read(stream:stream:r, imagetype?:string):map:reduceReads image data from a stream.
The format of the image data is determined by the byte sequence of the stream data and its file name.
You can also explicitly specify the image data format by the argument imagetype.
This method returns the reference to the target instance itself.
image#reducecolor(palette?:palette) {block?}Creates an image that reduces colors in the original image with a set of colors in the given palette. The specified palette would be associated with the created image.
If no argument is specified, the associated palette would be used. In this case, an error occurs if there's no palette associated.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#replacecolor(colorOrg:color, color:color, tolerance?:number):reduce
Replaces pixels that have a color matching colorOrg with the color.
The argument tolerance specifies an acceptable distance for the matching. If omitted, only an exact match is acceptable.
This method returns the reference to the target instance itself.
image#resize(width?:number, height?:number):map:[box,ratio] {block?}
Resizes the image to the size specified by width and height and returns the result.
- When both
widthandheightare specified, the image would be resized to the size. - When
widthis specified andheightis omitted ornil, the resized height would be calculated from the width so that they keep the same ratio as the original. - When
widthisnilandheightis specified, the resized width would be calculated from the height so that they keep the same ratio as the original.
The following attributes are acceptable:
:box.. When onlywidthis specified, the same value is set toheight.:ratio.. Treats values ofwidthandheightas magnifying ration instead of pixel size.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#rotate(rotate:number, background?:color):map {block?}Creates an image that rotates the original image by the specified angle.
The argument angle specifies the rotation angle in degree unit, and positive numbers for counterclockwise direction and negative for clockwise direction.
The created instance has a size that exactly fits the rotated image. The argument background specifies the color of pixels to fill the empty area that appears after rotation. If omitted, the color that has all elements set to zero is used for filling.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#scan(x?:number, y?:number, width?:number, height?:number, scandir?:symbol) {block?}Returns an iterator that scans pixels in the image.
The arguments x, y, width and height specify the image area to scan. The argument scandir specifies the scan direction and takes one of the following symbol:
| Symbol | Start Pos | Direction |
|---|---|---|
`left_top_horz |
left-top | horizontal |
`left_top_vert |
left-top | vertical |
`left_bottom_horz |
left-bottom | horizontal |
`left_bottom_vert |
left-bottom | vertical |
`right_top_horz |
right-top | horizontal |
`right_top_vert |
right-top | vertical |
`right_bottom_horz |
right-bottom | horizontal |
`right_bottom_vert |
right-bottom | vertical |
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
image#setalpha(a:number, color?:color, tolerance?:number):reduce
Replaces the alpha element of all the pixels in the image with the value specified by a.
If the argument color is specified, alpha element of pixels that match with that color would be replaced. The argument tolerance specifies the distance within which the color is determined as matched.
This method returns the reference to the target instance itself.
image#thumbnail(width?:number, height?:number):map:[box] {block?}
Resizes the image so that it fits within a rectangular area specified by width and height and returns the result.
If block is specified, it would be evaluated with a block parameter |img:image|, where img is the created instance. In this case, the block's result would become the function's returned value.
image#write(stream:stream:w, imagetype?:string):map:reduceWrites image data to a stream.
The format of the image data is determined by the stream's file name.
You can also explicitly specify the image data format by the argument imagetype.
This method returns the reference to the target instance itself.
5.33iterator/list Class
5.33.1Overview
The iterator class provides measures to operate an iterator, which iterates values that come from containers and streams.
The list class provides measures to handle a list structure, which stores values on memory that can be accessed by indexer.
5.33.2Iterator-specific Features
5.33.2.1Function to Create iterator Instance
iterator(value+) {block?}Creates an iterator that combines iterators given in the argument.
If an argument is not an iterator, that would be added as an element.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
5.33.2.2Method Specific to iterator Class
iterator#delay(delay:number) {block?}delay in seconds.
iterator#finite():reduceMarks the iterator as a finite one by clearing its infinite flag.
This method returns the target instance itself.
iterator#infinite():reduceMarks the iterator as an infinite one by setting its infinite flag.
This method returns the target instance itself.
iterator#isinfinite()
Returns true if the iterator is infinite one.
The trait of iterator's infinity is used to avoid an endless process by evaluating an infinite iterator. An attempt to evaluate an infinite iterator such as creation of a list from it would occur an error.
iterator#next()iterator#repeater()Makes the iterator behave as a "repeater". This would allow the iterator be evaulated when it appears as an element of another "repeater" iterator.
Below is an example:
x = repeat(3):iter {
['apple', 'orange', 'grape'].each()
}
println(x)
// Just prints iterator instance three times
// since x can't evaluate the internal iterator.
x = repeat(3):iter {
['apple', 'orange', 'grape'].each().repeater()
}
println(x)
// Prints 'apple', 'orange' and 'grape' three times
// after evaluating the internal iterator.
5.33.3List-specific Features
5.33.3.1Creating List
There are several ways to create a list.
[3, 1, 4, 1, 5, 9]
@{3, 1, 4, 1, 5, 9}
5.33.3.2Index Access
You can read and write element values in a list with an indexer by giving it an index number starting from zero. Below is an example:
x = [`A, `B, `C, `D, `E, `F]
println(x[2]) // prints `C
x[4] = `e // replaces `E with `e
5.33.3.3Function to Create list Instance
list(value+)xlist(value+)nil in its argument list. If a given value is a list or an iteartor, elements it contains are added to the created list.
set(iter+:iterator):[and,or,xor]Creates a new list that contains unique values from given iterators in its argument list.
In default, all the elements in each iterators are added to the created list. Specifying the following attributes would apply a filtering condition.
:and.. Elements that exist in all the iterators are added.:or.. All the elements are added. This is the default behavior.:xor.. Elements that exist in only one iterator are added.
xset(iter+:iterator):[and,or,xor]
Creates a new list that contains unique values except for nil from given iterators in its argument list.
In default, all the elements in each iterators are added to the created list. Specifying the following attributes would apply a filtering condition.
:and.. Elements that exist in all the iterators are added.:or.. All the elements are added. This is the default behavior.:xor.. Elements that exist in only one iterator are added.
5.33.3.4Method Specific to list Class
list#add(elem+):reducelist#append(elem+):reducelist#clear():reducelist#combination(n:number) {block?}Creates an iterator that generates lists that contain elements picked up from the original list in a combination manner.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
list#erase(idx*:number):reducelist#first()list#get(index:number):flat:maplist#insert(idx:number, elem+):reducelist#isempty()list#last()list#permutation(n?:number) {block?}Creates an iterator that generates lists that contain elements picked up from the original list in a permutation manner.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
list#put(index:number, value:nomap):map:reducelist#shift():[raise]list#shuffle():reducelist.zip(values+):static {block?}Creates an iterator generating lists that bind given argument values. When the value is a list or an iterator, each item in it would be zipped.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
5.33.4Method Common to Both list and iterator Classes
iterable#after(criteria) {block?}
Creates an iterator that picks up elements that appear at positions after the criteria is evaluated to be true.
You can specify a function, a list or an iterator as the criteria.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#align(n:number, value?) {block?}
Creates an iterator that returns the specified number of elements in the source iterator. If the number is larger than the length of the source iterator, the lacking part is filled with value. If the argument value is omitted, nil is used for the filling.
Below is an example to specify a number less than the source length:
x = [`A, `B, `C, `D, `E, `F].align(3)
// x generates `A, `B, `C.
Below is an example to specify a number that exceeds the source length:
x = [`A, `B, `C, `D, `E, `F].align(8)
// x generates `A, `B, `C, `D, `E, `F, nil, nil.
iterable#and()iterable#argmax():[indices,last_index]Returns a position index where the maximum value is found at first.
The following attributes modify the behavior:
:last_index.. returns an index where the maximum value is found at last.:indices.. returns a list of all indices where the maximum value is found.
Calling of methods iterable#argmas() and iteraboe#max() have the same effect when attributes are specified as follows:
iterable.argmax()anditerable.max():indexiterable.argmax():last_indexanditerable.max():last_indexiterable.argmax():indicesanditerable.max():indices
iterable#argmin():[indices,last_index]Returns a position index where the minimum value is found at first.
The following attributes modify the behavior:
:last_index.. returns an index where the minimum value is found at last.:indices.. returns a list of all indices where the minimum value is found.
Calling of methods iterable#argmas() and iteraboe#max() have the same effect when attributes are specified as follows:
iterable.argmax()anditerable.max():indexiterable.argmax():last_indexanditerable.max():last_indexiterable.argmax():indicesanditerable.max():indices
iterable#before(criteria) {block?}Creates an iterator that extracts elements in the iterable before criteria is evaluated as true. You can specify a function object, a list or an iterator as the criteria.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#contains(value)true if the specified value appears in the iterable.
iterable#count(criteria?)Returns a number of elements that matches the given criteria which is a single-argument function or a value.
When a function is applied, it counts the number of true after evaluating element value with the function. If a value is applied, it counts the number of elements that are equal to the value.
iterable#cycle(n?:number) {block?}Creates an iterator that iterates elements in the source iterator cyclically.
The argument n specifies the number of elements the created iterator returns. If omitted, it would iterates elements infinitely.
Below is an example:
x = [`A, `B, `C, `D, `E].cycle()
// x generates `A, `B, `C, `D, `E, `A, `B, `C, `D, `E, `A, `B, ..
iterable#each() {block?}Creates an iterator that iterates each element in the list.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#filter(criteria?) {block?}Creates an iterable that filters values in the source iterable by a criteria.
A criteria can be an iterable or a function instance.
- When the criteria is an iterable, the created iterator would scan the source and the criteria iterable simultaneously and would return a value of the source when the corresponding criteria value is evaluated as
true. - When the criteria is a function instance, the created iterator would give it a value of the source as an argument and would return the value when the function has returned
true.
Below is an example to use an iterable as its criteria:
x = [3, 1, 4, 1, 5, 9]
y = filter(x > 3)
// (x > 3) makes a list [false, false, true, false, true, true]
// y generates 4, 5, 9
Below is an example to use a function as its criteria:
x = [3, 1, 4, 1, 5, 9]
y = filter(&{$x > 3})
// y generates 4, 5, 9
iterable#find(criteria?):[index]iterable#flatten():[bfs,dfs] {block?}Creates an iterator that searches items recursively if they are lists or iterators.
Specifying an attribute could customize searching order as below:
:dfs.. Searches in depth-first order. This is the default behavior.:bfs.. Searches in breadth-first order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example:
x = [[`A, `B, `C], [`D, `E, [`F, `G, `H], `I, `J], `K, `L]
y = x.flattten():dfs
// y generates `A, `B, `C, `D, `E, `F, `G, `H, `I, `J, `K, `L
y = x.flatten():bfs
// y generates `K, `L, `A, `B, `C, `D, `E, `I, `J, `F, `G, `H
iterable#fold(n:number, nstep?:number):map:[iteritem,neat] {block?}
Creates an iterator that packs n elements of the source iterator into a list and returns it as its element.
The argument nstep specifies the shift amount to the next packing.If omitted, the next packing is shifted by n elements.
Specifying the attribute :iteritem returns an iterator as its element instead of a list
If the last packing doesn't satisfy n elements, its list would be shorter than n. When specifying the attribute :neat, such an immature list would be eliminated.
Following is an example to fold elements by 3:
x = [`A, `B, `C, `D, `E, `F, `G, `H].fold(3)
// x generates [`A, `B, `C], [`D, `E, `F], [`G, `H].
Following is an example to fold elements by 3 with a step of 2:
x = [`A, `B, `C, `D, `E, `F, `G, `H].fold(3, 2)
// x generates [`A, `B, `C], [`C, `D, `E], [`E, `F, `G], [`G, `H].
iterable#format(format:string):map {block?}
Creates an iterator that converts element values in the source iterable into strings depending on formatter specifier in format.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#head(n:number):map {block?}
Creates an iterator that takes the first n elements from the source iterable.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#join(sep?:string):map
Joins all the elements in the iterable as strings while inserting the specified separator sep and returns the result.
If an element is not a string value, it would be converted to a string before being joined.
iterable#joinb()binary values in the iterable and returns the result.
iterable#len()iterable#map(func:function) {block?}Creates an iterator that generates element values after applying the specfied function on them. The function must take one argument.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#max():[index,indices,last_index]Returns the maximum value in the iterable.
It would return a position index where the maximum value is found when one of the following attributes is specified:
:index.. an index of the maximum value.:last_index.. an index where the maximum value is found at last.:indices.. a list of all indices where the maximum value is found.
iterable#mean()Calculates an average of elements in the iterable.
It can work on an iterable with elements of type that supports addition and division operators. Below is a list of acceptable value types:
numbercomplexrational
iterable#min():[index,indices,last_index]Returns the minimum value in the iterable.
It would return a position index where the minimum value is found when one of the following attributes is specified:
:index.. an index of the minimum value.:last_index.. an index where the minimum value is found at last.:indices.. a list of all indices where the minimum value is found.
iterable#nilto(replace) {block?}nil in the source iterable to the specified value.
iterable#offset(n:number) {block?}
Creates an iterator that returns skips the first n elements in the source iterable.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example:
x = [`A, `B, `C, `D, `E, `F, `G, `H].offset(3)
// x generates `D, `E, `F, `G, `H
iterable#or()iterable#pack(format:string) {block?}
Creates a binary instance that has packed elements in the iterable according to specifiers in the format.
A specifier has a format of "nX" where X is a format character that represents a packing format and n is a number of packing size. The number can be omitted, and it would be treated as 1 in that case.
Following format characters would take a number value from the argument list and pack them into a binary sequence.
b.. A one-byte signed number.B.. A one-byte unsigned number.h.. A two-byte signed number.H.. A two-byte unsigned number.i.. A four-byte signed number.I.. A four-byte unsigned number.l.. A four-byte signed number.L.. A four-byte unsigned number.q.. A eight-byte signed number.Q.. A eight-byte unsigned number.f.. A float-typed number occupying four bytes.d.. A double-typed number occupying eight bytes.
As for them, the packing size n means the number of values to be packed.
Following format characters would take a string value from the argument list and pack them into a binary sequence.
s.. Packs a sequence of UTF-8 codes in the string. The packing sizenmeans the size of the room in bytes where the character codes are to be packed. Only the sequence within the allocated room would be packed. If the string length is smaller than the room, the lacking part would be filled with zero.c.. Picks the first byte of the string and packs it as a one-byte unsigned number. The packing sizenmeans the number of values to be packed.
Following format character would take no value from the argument list.
x.. Fills the binary with zero. The packing sizenmeans the size of the room in bytes to be filled with zero.
The default byte-order for numbers of two-byte, four-byte and eight-byte depends on the system the interpreter is currently running. You can change it by the following specifiers:
@.. System-dependent order.=.. System-dependent order.<.. Little endian>.. Big endian!.. Big endian
You can specify an asterisk character "*" for the number of packing size that picks that number from the argument list.
You can specify encoding name embraced with "{" and "}" in the format to change coding character set while packing a string with format character "s" from UTF-8.
iterable#pingpong(n?:number):[sticky,sticky@top,sticky@btm] {block?}Creates an iterator that iterates elements in the source iterator from top to bottom, and then from bottom to top repeatedly.
The argument n specifies the number of elements the created iterator returns. If omitted, it would iterates elements infinitely.
Below is an example:
x = [`A, `B, `C, `D, `E].pingpong()
// x generates `A, `B, `C, `D, `E, `D, `C, `B, `A, `B, ..
The following attributes specify whether the elements on top and bottom are duplicated:
:sticky.. Duplicate the top and bottom elements.:sticky@top.. Duplicate the top element.:sticky@btm.. Duplicate the bottom element.
Below is an example:
x = [`A, `B, `C, `D, `E].pingpong():sticky
// x generates `A, `B, `C, `D, `E, `E, `D, `C, `B, `A, `A, `B, ..
iterable#print(stream?:stream:w):void
Prints elements to the specified stream.
If omitted, they are printed to the standard output.
iterable#printf(format:string, stream?:stream:w):voiditerable#println(stream?:stream:w):voiditerable#rank(directive?) {block?}Creates an iterable of rank numbers for elements after sorting them.
In default, they are sorted in an ascending order. This means that, if two elements x and y has the relationship of x < y, x would be placed before y. You can change the order by specifying the argument directive with the following symbols:
`ascend.. Sorts in an ascending order. This is the default.`descend.. Sorts in a descending order.
You can also put a function to the argument directive that takes two arguments x and y and is expected to return numbers below:
x == y.. Zero.x < y.. A number less than zero.x > y.. A number greater than zero.
When an attribute :stable is specified, the original order shall be kept for elements that are determined as the same.
iterable#reduce(accum) {block}
Evaluates a block with a parameter format |value, accum| and leaves the result as the next accum value.
It returns the final accum value as its result.
Below is an example to calculate summation of the elements:
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = x.reduce(0) {|value, accum| value + accum}
// n is 55
iterable#replace(value, replace) {block?}
Creates an iterator that replaces the value in the original iterablewith the value of replace.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#reverse() {block?}Creates an iterator that iterates elements in the source iterable from tail to top.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#roundoff(threshold:number => 1e-10) {block?}
Creates an iterator that replaces a number with zero if it is less than the specified threshold.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#runlength() {block?}
Creates an iterator that counts the number of consecutive same value and generates elements in a form of [cnt, value] where cnt indicates how many value appears in a row.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example:
x = [`A, `A, `B, `C, `C, `C, `D, `D].runlength()
// x generates [2, `A], [1, `B], [3, `C], [2, `D]
iterable#since(criteria) {block?}Creates an iterator that picks up each element in the iterable since criteria is evaluated as true. You can specify a function object, a list or an iterator as the criteria.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#skip(n:number) {block?}
Creates an iterator that skips n elements before picking up next element.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example:
x = [`A, `B, `C, `D, `E, `F, `G, `H].skip(2)
// x generates `A, `D, `G
iterable#skipnil() {block?}
Creates an iterator that skips nil in the source iterable.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example:
x = [`A, nil, `C, nil, nil, `F, nil, `H].skipnil()
// x generates `A, `C, `F, `H
iterable#sort(directive?, keys[]?):[stable] {block?}Creates an iterator of elements after sorting them.
In default, they are sorted in an ascending order. This means that, if two elements x and y has the relationship of x < y, x would be placed before y. You can change the order by specifying the argument directive with the following symbols:
`ascend.. Sorts in an ascending order. This is the default.`descend.. Sorts in a descending order.
You can also put a function to the argument directive that takes two arguments x and y and is expected to return numbers below:
x == y.. Zero.x < y.. A number less than zero.x > y.. A number greater than zero.
When an attribute :stable is specified, the original order shall be kept for elements that are determined as the same. If the argument keys is specified, it would be used as a key instead of element values.
iterable#std():[p]iterable#sum()Calculates a summation of elements in the iterable.
It can work on an iterable with elements of a value type that supports addition operator. Below is a list of acceptable value types:
numbercomplexstringrationaltimedelta
iterable#tail(n:number) {block?}
Creates an iterator that takes the last n elements from the source iterable.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#until(criteria) {block?}Creates an iterator that picks up each element in the list until criteria is evaluated as true. You can specify a function object, a list or an iterator as the criteria.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
iterable#var():[p]iterable#while (criteria) {block?}Creates an iterator that picks up each element in the list while criteria is evaluated as true. You can specify a function object, a list or an iterator as the criteria.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
5.34memory Class
5.34.1Overview
An instance of the memory class represents a memory that is stored in array instances.
5.34.2Property
A memory instance has the following properties:
memory#p … pointer [read-only]pointer instance that accesses the memory. This result is equivalent to that of calling the method memory#pointer().
memory#size … number [read-only]5.34.3Constructor
memory(bytes:number):map {block?}5.34.4Method
memory#array@int8():map {block?}array@int8 instance that accesses the content of the target memory instance.
memory#array@uint8():map {block?}array@uint8 instance that accesses the content of the target memory instance.
memory#array@int16():map {block?}array@int16 instance that accesses the content of the target memory instance.
memory#array@uint16():map {block?}array@uint16 instance that accesses the content of the target memory instance.
memory#array@int32():map {block?}array@int32 instance that accesses the content of the target memory instance.
memory#array@uint32():map {block?}array@uint32 instance that accesses the content of the target memory instance.
memory#array@int64():map {block?}array@int64 instance that accesses the content of the target memory instance.
memory#array@uint64():map {block?}array@uint64 instance that accesses the content of the target memory instance.
memory#array@float():map {block?}array@float instance that accesses the content of the target memory instance.
memory#array@double():map {block?}array@double instance that accesses the content of the target memory instance.
memory#dump(stream?:stream:w):void:[upper]
Prints a hexadecimal dump from the content of the memory to the standard output. If the argument stream is specified, the result would be output to the stream.
In default, hexadecimal digit are printed with lower-case characters. Specifying an attribute :upper would output them with upper-case characters instead.
Example:
>>> b'A quick brown fox jumps over the lazy dog.'.dump():upper
41 20 71 75 69 63 6B 20 62 72 6F 77 6E 20 66 6F A quick brown fo
78 20 6A 75 6D 70 73 20 6F 76 65 72 20 74 68 65 x jumps over the
20 6C 61 7A 79 20 64 6F 67 2E lazy dog.
memory#pointer(offset?:number) {block?}
Returns a pointer instance that has an initial offset specified by the argument offset. If the argument is omitted, it would return a pointer instance that points to the top of the memory.
If block is specified, it would be evaluated with a block parameter |p:pointer|, where p is the created instance. In this case, the block's result would become the function's returned value.
5.35nil Class
5.35.1Overview
The nil class is the class of nil value that is usually used as an invalid value. In a logical operation, the nil value is recognized as false.
5.36number Class
5.36.1Overview
The number class is a type of number values. A number literal would create a number instance.
5.36.2Method
number.roundoff(threshold:number => 1e-10)5.37operator Class
5.37.1Overview
The operator class provides measures to assign operators with a user-defined procedure.
5.37.2Property
An operator instance has the following properties:
operator#symbol … symbol [read-only]symbol instance that represents the operator's type.
5.37.3Constructor
operator(symbol:symbol):map {block?}
Creates an operator instance that is associated with the specified symbol.
If block is specified, it would be evaluated with a block parameter |op:operator|, where op is the created instance. In this case, the block's result would become the function's returned value.
Below is an example to create an operator instance that is associated with the plus symbol.
op = operator(`+)
5.37.4Method
operator#assign(type_l:expr, type_r?:expr):map:void {block}
Associates the operator instance with a procedure described in block that takes values as a block parameter and returns its operation result.
Some operator instances have two forms of expression: unary and binary. This method assignes the procedure to one of them according to how it takes its arguments as below:
operator#assign(type:expr).. Assigns procedure to the unary form.operator#assign(type_l:expr, type_r:expr).. Assignes procedure to the binary form.
They take different format of block parameters as below:
|value|.. For unary form.|value_l, value_r|.. For binary form.
Below is an example to assign a procedure to a unary form of operator -.
operator(`-).assign(`string) = {|value|
// any job
}
Below is an example to assign a procedure to a binary form of operator -.
operator(`-).assign(`string, `number) = {|value_l, value_r|
// any job
}
operator#entries(type?:symbol)Returns a list that contains type expressions that the operator can accept as its arguments.
The argument type takes a symbol `binary or `unary.
- If it's omitted or specified with
`binary, the method would return a list of pairs of type expressions for its left element and right one. - If it's specified with
`unary, the method would return a list of type expressions for its single element.
5.38optimizer Class
5.38.1Overview
5.38.2Constructor
An optimizer instance is constructed by following functions:
optimizer@adagrad(learning_rate:number, epsilon?:number):map {block?}
Creates an optimizer instance that uses AdaGrad approach for optimization.
The argument learning_rate indicates the learning rate per one training session.
The argumnent epsilon is a value that is added to the denominator in a divination to avoid zero-divided error. The default is 1e-7.
optimizer@adam():map {block?}optimizer@gradient_descent(learning_rate:number):map {block?}
Creates an optimizer instance that uses gradient descent approach for optimization.
The argument learning_rate indicates the learning rate per one training session.
optimizer@momentum(learning_rate:number, momentum?:number):map {block?}
Creates an optimizer instance that uses AdaGrad approach for optimization.
The argument learning_rate indicates the learning rate per one training session.
The argumnent momentum is a momentum parameter and has a default value of 0.9.
optimizer@nesterov():map {block?}optimizer@none():map {block?}optimizer@rmsprop():map {block?}5.38.3Method
The optimizer class has following methods:
optimizer#reset():voidoptimizer#update(array:array, array_grad:array):voidarray's value by the optimizer calculation using the gradient information in array_grad.
5.39palette Class
5.39.1Overview
The palette instance has a set of color instance.
5.39.2Constructor
palette(type) {block?}
Creates a palette instance.
If block is specified, it would be evaluated with a block parameter |plt:palette|, where plt is the created instance. In this case, the block's result would become the function's returned value.
This function can be called in the following two forms:
palette(n:number).. Creates an instance with the specified number of entries. All the entries are initialized with a color of black.palette(type:symbol).. Creates an instance initialized with a pre-defined set of entries associated with the specified symbol.
In the second form, it can take one of the following symbols:
`basic.. A palette with 16 basic colors that are:color.black,color.maroon,color.green,color.olive,color.navy,color.purple,color.teal,color.gray,color.silver,color.red,color.lime,color.yellow,color.blue,color.fuchsia,color.aquaandcolor.white.`win256.. A palette with 256 colors defined by Windows.`websafe.. A palette with 216 colors that assure to be displayed correctly in any Web environments. It actually has 256 entries though the last 40 entries are initialized with black.
5.39.3Method
palette#each() {block?}Creates an iterator that iterates each element in the palette.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
palette#nearest(color:color):map:[index]
Returns a color instance in the palette that is the nearest with the specified color.
If the attribute :index is specified, it would return an index of the nearst entry instead of its color instance.
palette#shrink():reduce:[align]palette#updateby(image_or_palette):reduce:[align,shrink]Updates palette entries according to color data in an image or a palette.
The order of existing entries will be kept intact. If attribute shrink is specified, the whole size will be shrinked to a number powered by two that is enough to contain unique entries.
5.40pointer Class
5.40.1Overview
The pointer class provides measures to read and write content in a binary and memory instance.
5.40.2Property
A pointer instance has following properties:
pointer#offset … number [read/write]pointer#size … number [read-only]pointer#size@all … number [read-only]p.offset + p.size where p is a pointer instance.
pointer#target … any [read-only]binary or memory.
5.40.3Constructor
A pointer instance is constructed by the following function:
pointer(org:pointer):map {block?}
Creates a pointer instance that is cloned from the given instance org. You can use this to cast a binary and memory instance to the pointer.
If block is specified, it would be evaluated with a block parameter |ptr:pointer|, where ptr is the created instance. In this case, the block's result would become the function's returned value.
5.40.4Method
The pointer class has following methods:
pointer#copyfrom(src:pointer, bytes?:number):map:reduce
Copies data from src to the target pointer.
If the argument bytes is specified, it would limit the size of data to be copied. Otherwise, all the data pointerd by src is to be copied.
This method returns a reference to the target instance itself.
pointer#copyto(dst:pointer, bytes?:number):map:reduce
Copies data from the target pointer to dst.
If the argument bytes is specified, it would limit the size of data to be copied. Otherwise, all the data pointerd by the target instance is to be copied.
This method returns a reference to the target instance itself.
pointer#decode(codec:codec, bytes?:number) {block?}
Decodes the content of the pointer as a sequence of string characters using codec and returns the result in string.
If the argument bytes is specified, it would limit the size of data to be decoded. Otherwise, all the data pointerd by the target instance is to be decoded.
If block is specified, it would be evaluated with a block parameter |str:string|, where str is the created instance. In this case, the block's result would become the function's returned value.
pointer#dump(stream?:stream:w, bytes?:number):reduce:[upper]
Prints a hexadecimal dump from the content of the pointer to the standard output. If the argument stream is specified, the result would be output to the stream.
If the argument bytes is specified, it would limit the size of data to be dumped. Otherwise, all the data pointerd by the target instance is to be dumped.
In default, hexadecimal digit are printed with lower-case characters. Specifying an attribute :upper would output them with upper-case characters instead.
Example:
>>> b'A quick brown fox jumps over the lazy dog.'.p.dump():upper
41 20 71 75 69 63 6B 20 62 72 6F 77 6E 20 66 6F A quick brown fo
78 20 6A 75 6D 70 73 20 6F 76 65 72 20 74 68 65 x jumps over the
20 6C 61 7A 79 20 64 6F 67 2E lazy dog.
pointer#encodeuri(bytes?:number) {block?}Returns a string in which non-URIC characters are converted to percent-encoded string.
For example, b'"Hello"'.p.encodeuri() would return '%22Hello%22'.
If block is specified, it would be evaluated with a block parameter |str:string|, where str is the created instance. In this case, the block's result would become the function's returned value.
pointer#each@int8():[be] {block?}Creates an iterator that extracts numbers in size of int8 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@uint8():[be] {block?}Creates an iterator that extracts numbers in size of uint8 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@int16():[be] {block?}Creates an iterator that extracts numbers in size of int16 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@uint16():[be] {block?}Creates an iterator that extracts numbers in size of uint16 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@int32():[be] {block?}Creates an iterator that extracts numbers in size of int32 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@uint32():[be] {block?}Creates an iterator that extracts numbers in size of uint32 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@int64():[be] {block?}Creates an iterator that extracts numbers in size of int64 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@uint64():[be] {block?}Creates an iterator that extracts numbers in size of uint64 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@float():[be] {block?}Creates an iterator that extracts numbers in size of float from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#each@double():[be] {block?}Creates an iterator that extracts numbers in size of double from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
pointer#forward(distance:number):reduce
Put the pointer offset forward by distance. If a negative number is specified for the argument, the offset would be put backward.
An error would occur when the pointer's offset becomes a negative value while it would be no error when the offset exceeds the target maximum range.
This method returns a reference to the target instance itself.
pointer#get@int8():[be,nil,stay] {block?}Returns an extracted number in size of int8 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@uint8():[be,nil,stay] {block?}Returns an extracted number in size of uint8 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@int16():[be,nil,stay] {block?}Returns an extracted number in size of int16 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@uint16():[be,nil,stay] {block?}Returns an extracted number in size of uint16 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@int32():[be,nil,stay] {block?}Returns an extracted number in size of int32 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@uint32():[be,nil,stay] {block?}Returns an extracted number in size of uint32 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@int64():[be,nil,stay] {block?}Returns an extracted number in size of int64 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@uint64():[be,nil,stay] {block?}Returns an extracted number in size of uint64 from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@float():[be,nil,stay] {block?}Returns an extracted number in size of float from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#get@double():[be,nil,stay] {block?}Returns an extracted number in size of double from the current pointer position.
In default, it assumes the byte seqeuces are ordered in little-endian. You can specify :be attribute to extract them in big-endian order.
If block is specified, it would be evaluated with a block parameter |n:number|, where n is the created instance. In this case, the block's result would become the function's returned value.
pointer#head():reduceMoves the pointer position to the beginning.
This method returns a reference to the target instance itself.
pointer#hex(bytes?:number):[carray,cstr,upper] {block?}Converts the binary data into a hexadecimal string.
In default, the result string is a sequence of joined hexadecimal values without any space. You can specify the following attribute to change the format:
:cstr.. Format of C string.:carray.. Format of C array.
Alphabet characters are described in lower characters unless the attribute :upper is specified.
If block is specified, it would be evaluated with a block parameter |str:string|, where str is the created instance. In this case, the block's result would become the function's returned value.
Example:
| Code | Result |
|---|---|
b'\x01\x23\xab\xcd'.p.hex() |
'0123abcd' |
b'\x01\x23\xab\xcd'.p.hex():upper |
'0123ABCD' |
b'\x01\x23\xab\xcd'.p.hex():cstr |
'\\x01\\x23\\xab\\xcd' |
b'\x01\x23\xab\xcd'.p.hex():carray |
'0x01, 0x23, 0xab, 0xcd' |
pointer#pack(format:string, values+):reduce:[stay]
Packs values in the argument list according to specifiers in the format into a binary and adds it to where the pointer points. The pointer offset is automatically incremented by the added length unless :stay attribute is specified.
This method returns a reference to the target instance itself.
A specifier has a format of "nX" where X is a format character that represents a packing format and n is a number of packing size. The number can be omitted, and it would be treated as 1 in that case.
Following format characters would take a number value from the argument list and pack them into a binary sequence.
b.. One-byte signed number.B.. One-byte unsigned number.h.. Two-byte signed number.H.. Two-byte unsigned number.i.. Four-byte signed number.I.. Four-byte unsigned number.l.. Four-byte signed number.L.. Four-byte unsigned number.q.. Eight-byte signed number.Q.. Eight-byte unsigned number.f.. Float-typed number occupying four bytes.d.. Double-typed number occupying eight bytes.
As for them, the packing size n means the number of values to be packed.
Following format characters would take a string value from the argument list and pack them into a binary sequence.
s.. Packs a sequence of UTF-8 codes in the string. The packing sizenmeans the size of the room in bytes where the character codes are to be packed. Only the sequence within the allocated room would be packed. If the string length is smaller than the room, the lacking part would be filled with zero.c.. Picks the first byte of the string and packs it as a one-byte unsigned number. The packing sizenmeans the number of values to be packed.
Following format character would take no value from the argument list.
x.. Fills the binary with zero. The packing sizenmeans the size of the room in bytes to be filled with zero.
The default byte-order for numbers of two-byte, four-byte and eight-byte depends on the system the interpreter is currently running. You can change it by the following specifiers:
@.. System-dependent order.=.. System-dependent order.<.. Little endian>.. Big endian!.. Big endian
You can specify an asterisk character "*" for the number of packing size that picks that number from the argument list.
You can specify encoding name embraced with "{" and "}" in the format to change coding character set from UTF-8 while packing a string with format character "s".
pointer#put@int8(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of int8.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@uint8(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of uint8.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@int16(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of int16.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@uint16(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of uint16.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@int32(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of int32.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@uint32(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of uint32.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@int64(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of int64.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@uint64(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of uint64.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@float(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of float.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#put@double(n:number):map:reduce:[be,stay]Stores the specified number to the current pointer position in size of double.
In default, it stores the byte sequences in the order of little-endian. You can specify :be sttribute to store them in big-endian order.
This method returns a reference to the target instance itself.
pointer#reader() {block?}stream instance with which you can read data from the memory pointerd by the pointer. If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
pointer#seek(offset:number):reduce
Moves the pointer position to the specified offset.
This method returns a reference to the target instance itself.
pointer#tail():reduceMoves the pointer position to the end.
This method returns a reference to the target instance itself.
pointer#unpack(format:string, values*:number):[nil,stay] {block?}
Extracts values from data sequence pointed by the pointer instance according to specifiers in the format and returns a list containing the values.
A specifier has a format of "nX" where X is a format character that represents a packing format and n is a number of packing size. The number can be omitted, and it would be treated as 1 in that case.
Following format characters would extract an integer or float value of specified size from the binary and returns a number value.
b.. One-byte signed number.B.. One-byte unsigned number.h.. Two-byte signed number.H.. Two-byte unsigned number.i.. Four-byte signed number.I.. Four-byte unsigned number.l.. Four-byte signed number.L.. Four-byte unsigned number.q.. Eight-byte signed number.Q.. Eight-byte unsigned number.f.. Float-typed number occupying four bytes.d.. Double-typed number occupying eight bytes.
As for them, the packing size n means the number of values to be extracted.
Following format characters would extract a string sequence from the binary and returns a string value.
s.. Extracts a sequence of UTF-8 codes and returnsstringinstance containing it. The unpacking sizenmeans the size of the room in bytes where the character codes are to be unpacked.c.. Extracts a one-byte unsigned number and returns astringinstance containing it. The unpacking sizenmeans the number of values to be extracted.
Following format character would not return any value.
x.. Advances the address by one byte. If the unpacking sizenis specifies, it would advance the address bynbytes.
The default byte-order for numbers of two-byte, four-byte and eight-byte depends on the system the interpreter is currently running. You can change it by the following specifiers:
@.. System-dependent order.=.. System-dependent order.<.. Little endian>.. Big endian!.. Big endian
You can specify an asterisk character "*" for the number of unpacking size that picks that number from the argument list.
You can specify encoding name embraced with "{" and "}" in the format to change coding character set from UTF-8 while extracting a string with format character "s".
An error occurs if the binary size is smaller than the format reqeusts. If the attribute :nil is specified, nil value would be returned for such a case.
If block is specified, it would be evaluated with a block parameter |list:list|, where list is the created instance. In this case, the block's result would become the function's returned value.
pointer#unpacks(format:string, values*:number):map {block?}
Returns an iterator that extracts values from data pointed by the pointer instance according to specifiers in format.
For detailed information about specifiers, see the help of pointer#unpack().
If block is specified, it would be evaluated with a block parameter |iter:iterator|, where iter is the created instance. In this case, the block's result would become the function's returned value.
pointer#writer() {block?}stream instance with which you can append data to the memory pointed by the pointer. If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
5.40.5Cast Operation
A function that expects a pointer instance in its argument can also take a value of binary and memory.
With the above casting feature, you can call a function f(p:pointer) that takes a pointer instance in its argument as below:
b = b'\x01\x23\x45\x67\x89\xab', f(b)m = memory(32), f(m)
5.41propdeclaration Class
5.41.1Overview
The propdeclaration class provides information such as the name and the read/write attribute of property that is stored in various objects.
You can get an iterator of propdeclaration by calling object#__propdecls__().
5.41.2Property
A propdeclaration instance has the following properties:
propdeclaration#dispname … string [read-only]propdeclaration#fullname … string [read-only]propdeclaration#name … string [read-only]propdeclaration#readable … boolean [read-only]true if it is readable, false otherwise.
propdeclaration#symbol … symbol [read-only]symbol instance.
propdeclaration#type … string [read-only]propdeclaration#writable … boolean [read-only]true if it is readable, false otherwise.
5.41.3Method
The propdeclaration class provides the following methods:
propdeclaration#gethelp(lang?:symbol):map {block?}
Get a help instance assosicated with the property.
The argument lang specifies the language of the document, such as en and ja.
If block is specified, it would be evaluated with a block parameter |help:help|, where help is the created instance. In this case, the block's result would become the function's returned value.
5.42rational Class
5.42.1Overview
The rational class provides measures to handle rational numbers.
You can create a rational instance with following ways:
- Use
rational()function. - Append
rsuffix after a number literal.
Below are examples to realize a common fraction two-thirds:
rational(2, 3)
2r / 3
2 / 3r
5.42.2Constructor
rational(numer:number, denom?:number):map {block?}
Creates a rational value from given numerator numer and denominator denom.
If the argument denom is omitted, one is set as its denominator.
If block is specified, it would be evaluated with a block parameter |r:rational|, where r is the created instance. In this case, the block's result would become the function's returned value.
5.42.3Method
rational.reduce()5.43semaphore Class
5.43.1Overview
5.43.2Constructor
semaphore()5.43.3Method
semaphore#release()semaphore#session() {block}semaphore#wait()5.44stream Class
5.44.1Overview
The stream class provides methods to read and write data through a stream, an abstract structure to handle a byte sequence. It also provides information of the stream such as the pathname and the creation date and time.
You can specify a proper codec when creating the stream instance, which is used to decode/encode character codes that appear in the stream. Features of codec would affect on functions and methods that handle text data like follows:
- Decode
- readlines()
- stream#readchar()
- stream#readline()
- stream#readlines()
- stream#readtext()
- Encode
- operator
<< - stream#print()
- stream#printf()
- stream#println()
- operator
5.44.2Property
A stream instance has the following properties:
stream#codec … codec [read-only]codec instance associated with the stream.
stream#identifier … string [read-only]stream#name … string [read-only]stream#readable … boolean [read-only]stream#stat … any [read-only]stream#writable … boolean [read-only]5.44.3Operator
You can use the operator "<<" to output a content of a value to a stream. It comes like "stream << obj" where obj is converted to a string before output to the stream.
sys.stdout << 'Hello World.'
Since the operator returns the stream instance specified on the left as its result, you can chain multiple operations as below:
sys.stdout << 'First' << 'Second'
5.44.4Cast Operation
A function that expects a stream instance in its argument can also take a value of string and binary as below:
string.. Recognized thestringas a path name from whichstreaminstance is created.binary.. Creates astreaminstance that reads or modifies the content of the specifiedbinarydata. If thebinarydata is a constant one, which might be created from a binary literal such asb'\x00\x12\x34\x56', the stream is created with read-only attribute.
Using the above casting feature, you can call a function f(stream:stream) that takes a stream instance in its argument as below:
f(stream('foo.txt')).. The most explicit way.f('foo.txt').. Implicit casting fromstringtostream.f(b'\x00\x12\x34\x56').. Implicit casting frombinarytostreamthat reads the content.
5.44.5Constructor
stream(pathname:string, mode?:string, codec?:codec):map {block?}
Creates a stream instance from the specified pathname.
The argument mode takes one of the strings that specifies what access should be allowed with the stream. If omitted, the stream would be opened with read mode.
'r'.. read'w'.. write'a'.. append
The argument codec specifies a name of the character codec that converts between the stream's character code and UTF-8, which is a code used in the iterpreter's internal process.
If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
You can also call open() function that is just an alias of stream() to create a stream instance.
5.44.6Utility Function
readlines(stream?:stream:r):[chop] {block?}Creates an iterator that reads text from the specified stream line by line.
If attribute :chop is specified, it eliminates an end-of-line character that appears at the end of each line.
This function decodes character codes in the stream using codec instance that is specified when the stream instance is created.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
5.44.7Method
stream#addcr(flag?:boolean):reduce
The codec's encoder in the stream has a feature to add a CR code (0x0d) before a LF code (0x0a) so that the lines are joined with CR-LF codes in the encoded result. This method enables or disables the feature.
- To enable it, call the method with the argument
flagset totrueor without any argument. - To disable it, call the method with the argument
flagset tofalse.
stream#close():voidstream#compare(stream:stream:r):maptrue if there's no difference between the binary sequences of the target stream instance and that of stream in the argument.
stream.copy(src:stream:r, dst:stream:w, bytesunit:number => 65536):static:map:void:[finalize] {block?}
Copies the content in src to the stream dst.
The copy process is done by the following steps:
- Reads data from stream
srcinto a buffer with the size specified bybytesunit. - (1) If
blockis specified, it would be evaluated with a block parameter|buff:binary|wherebuffcontains the read data. When the block's result is abinaryinstance, the content would be written to the streamdst. Otherwise, the read data would be written to streamdst. (2) Ifblockis not specified, the read data would be written to streamdst. - Continues from step 1 to 2 until data from
srcruns out.
If the attribute :finalize is specified, some finalizing process such as copying the time stamp and attributes will be applied at the end.
This works the same way as stream#copyfrom() and stream#copyto().
stream#copyfrom(src:stream:r, bytesunit:number => 65536):map:reduce:[finalize] {block?}
Copies the content in src to target stream instance.
The copy process is done by the following steps:
- Reads data from stream
srcinto a buffer with the size specified bybytesunit. - (1) If
blockis specified, it would be evaluated with a block parameter|buff:binary|wherebuffcontains the read data. When the block's result is abinaryinstance, the content would be written to the target stream. Otherwise, the read data would be written to the target stream. (2) Ifblockis not specified, the read data would be written to the target stream. - Continues from step 1 to 2 until data from
srcruns out.
If the attribute :finalize is specified, some finalizing process such as copying the time stamp and attributes will be applied at the end.
This works the same way as stream.copy() and stream#copyto().
stream#copyto(dst:stream:w, bytesunit:number => 65536):map:reduce:[finalize] {block?}
Copies the content in the target stream to the stream dst.
The copy process is done by the following steps:
- Reads data from the target stream into a buffer with the size specified by
bytesunit. - (1) If
blockis specified, it would be evaluated with a block parameter|buff:binary|wherebuffcontains the read data. When the block's result is abinaryinstance, the content would be written to the streamdst. Otherwise, the read data would be written to streamdst. (2) Ifblockis not specified, the read data would be written to streamdst. - Continues from step 1 to 2 until data from the target stream runs out.
If the attribute :finalize is specified, some finalizing process such as copying the time stamp and attributes will be applied at the end.
This works the same way as stream.copy() and stream#copyfrom().
stream#delcr(flag?:boolean):reduce
The codec's decoder in the stream has a feature to delete a CR code (0x0d) before a LF code (0x0a) so that the lines are joined with LF code in the decoded result. This method enables or disables the feature.
- To enable it, call the method with the argument
flagset totrueor without any argument. - To disable it, call the method with the argument
flagset tofalse.
stream#deserialize()stream#flush():voidstream#peek(bytes?:number)binary instance that contains it. This doesn't move the stream's current file position.
stream#print(values*):map:void
Prints out values to the stream instance after converting them to strings.
This function encodes character codes in the string using codec instance that is specified when the stream instance is created.
stream#printf(format:string, values*):map:void
Prints out values to the stream instance according to formatter specifiers in format.
Refer to the help of printf() function to see information about formatter specifiers.
This function encodes character codes in the string using codec instance that is specified when the stream instance is created.
stream#println(values*):map:void
Prints out values and an end-of-line character to the stream instanceafter converting them to strings.
This function encodes character codes in the string using codec instance that is specified when the stream instance is created.
stream#read(bytes?:number) {block?}
Reads specified length of data from the stream and returns a binary instance that contains it. If the argument bytes is omitted, all the data available from the stream would be read.
If block is specified, it would be evaluated with a block parameter |buff:binary|, where buff is the created instance. In this case, the block's result would become the function's returned value.
stream#readchar() {block?}
Reads one character from the stream and returns a string instance that contains it.
This method decodes character codes in the stream using codec instance that is specified when the stream instance is created.
If block is specified, it would be evaluated with a block parameter |ch:string|, where ch is the created instance. In this case, the block's result would become the function's returned value.
stream#readline():[chop] {block?}
Reads one line from the stream and returns a string instance that contains it.
If the attribute :chop is specified, it would remove the last new line character from the result. This method decodes character codes in the stream using codec instance that is specified when the stream instance is created.
If block is specified, it would be evaluated with a block parameter |line:string|, where line is the created instance. In this case, the block's result would become the function's returned value.
stream#readlines(nlines?:number):[chop] {block?}Creates an iterator that reads text from the specified stream line by line.
The argument nlines specifies how many lines should be read from the stream. If omitted, it would read all the lines.
If attribute :chop is specified, it eliminates an end-of-line character that appears at the end of each line.
This method decodes character codes in the stream using codec instance that is specified when the stream instance is created.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
stream#readtext() {block?}
Reads the whole data in the stream as a text sequence and returns a string instance that contains it. This method decodes character codes in the stream using codec instance that is specified when the stream instance is created.
If block is specified, it would be evaluated with a block parameter |text:string|, where text is the created instance. In this case, the block's result would become the function's returned value.
stream#seek(offset:number, origin?:symbol):reduce
Seeks the current file position to the offset specified by the argument offset.
The argument origin specifies the meaning of offset value as follows:
set` ... `offset` is an absolute offset from the begining of the stream.cur` ... `offset` is a relative offset from the current position.
This method returns the target stream instance itself.
stream#serialize(value):voidstream#setcodec(codec:codec:nil):reduce
Sets codec instance to the target stream. If nil is specified for the argument, the current codec instance would be removed.
This method returns the target stream instance itself.
stream#tell()stream#write(ptr:pointer, bytes?:number):reduceptr to the stream. The argument bytes limits the number of data that is to be written to the stream.
5.45string Class
5.45.1Overview
The string class provides measures to operate on strings.
You can create a string instance by embracing a sequence of characters with a pair of single- or double-quotes.
'Hello World'
"Hello World"
If you need to declare a string that contains multiple lines, embrace it with a pair of sequences of three single- or double-quotes.
R"""
first line
second line
third line
"""
5.45.2Suffix Management
When an string literal is suffixed by a character $, a handler registered by string.translate() function that is supposed to translate the string into other natural languages would be evaluated.
5.45.3Method
string#align(width:number, padding:string => ' '):map:[center,left,right] {block?}
Align the string to the left, right or center within the specified width and returns the result.
The following attributes specify the alignment position:
:center.. Aligns to the center. This is the default.:left.. Aligns to the left:right.. Aligns to the right
If the string width is narrower than the specified width, nothing would be done.
It uses a string specified by the argument padding to fill lacking spaces. If omitted, a white space is used for padding.
This method takes into account the character width based on the specification of East Asian Width. A kanji-character occupies two characters in width.
string.binary() {block?}binary instance.
string#capitalize() {block?}string#chop(suffix*:string):[eol,icase] {block?}Returns a string that removes a last character.
If an attribute :eol is specified, only the end-of-line character shall be removed. In this case, if the end-of-line has a sequence of CR-LF, CR code shall be removed as well.
string#decodeuri() {block?}string#each():map:[utf32,utf8] {block?}Creates an iterator generating strings of each character in the original one.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
string#eachline(nlines?:number):[chop] {block?}Creates an iterator generating strings of each line in the original one.
In default, end-of-line characters are involved in the result. You can eliminates them by specifying :chop attribute.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
string#embed(dst?:stream:w):[lasteol,noindent]Evaluates a string that contains embedded scripts and renders the result to the specified stream.
If the stream is omitted, the function returns the rendered result as a string.
Calling this method is equivalent to calling a method string#template() to create a template instance on which a method template#render() is applied afterward.
string.encode(codec:codec) {block?}codec and return the result as a binary.
string#encodeuri() {block?}string#endswith(suffix:string, endpos?:number):map:[icase,rest]
Returns true if the string ends with suffix.
If attribute :rest is specified, it returns the rest part if the string ends with suffix, or nil otherewise. You can specify a bottom position for the matching by an argument endpos.
With an attribute :icase, character cases are ignored while matching.
string#escapehtml():[quote] {block?}:quote is specified, a double-quotation character would be converted to an entity symbol """.
string#find(sub:string, pos:number => 0):map:[icase,rev]Finds a sub string from the string and returns its position.
Number of position starts from zero. You can specify a position to start finding by an argument pos. It returns nil if finding fails.
With an attribute :icase, case of characters are ignored while finding.
When an attribute :rev, finding starts from tail of the string
string#fold(len:number, step?:number):[neat] {block?}Creates an iterator that folds the source string by the specified length.
The argument step specifies the length of advancement for the next folding point. If omitted, it would be the same amount as len.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
string#foldw(width:number):[padding] {block?}Creates an iterator that folds the source string by the specified width.
This method takes into account the character width based on the specification of East Asian Width.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
string#format(values*):mapvalues into a string depending on formatter specifiers in it.
string#isempty()true if the string is empty.
string#left(len?:number):mapExtracts the specified length of string from left of the source string.
If the argument is omitted, it would return whole the source string.
string#len()string#lower()string#mid(pos:number, len?:number):map {block?}
Extracts the specified length of string from the position pos and returns the result.
If the argument len is omitted, it returns a string from pos to the end. The number of an argument pos starts from zero.
Below are examples:
'Hello world'.mid(3, 2) // 'lo'
'Hello world'.mid(5) // 'world'
string.print(stream?:stream:w):void
Prints out the string to the specified stream.
If the argument is omitted, it would print to the standard output.
string.println(stream?:stream:w):void
Prints out the string and a line-break to the specified stream.
If the argument is omitted, it would print to the standard output.
string#reader() {block?}
Returns a stream instance that reads the string content as a binary sequence.
If block is specified, it would be evaluated with a block parameter |s:stream|, where s is the created instance. In this case, the block's result would become the function's returned value.
string#replace(match:string, sub:string, count?:number):map:[icase] {block?}
Replaces sub strings that matches the string match with a string specified by sub and returns the result.
The argument count limits the maximum number of substitution. If omitted, there's no limit of the work.
With an attribute :icase, character cases are ignored while matching strings.
If block is specified, it would be evaluated with a block parameter |result:string, replaced:boolean|, where result is the result string and replaced indicates if there is any change between the result and its original string. In this case, the block's result would become the function's returned value.
string#replaces(map[]:string, count?:number):map:[icase] {block?}Replaces string parts according to a list of pairs of a matching and a substituting string and returns the result.
The argument map is a list of match-substitution paris like [match1, sub1, match2, sub2, ..] with which a sub string that matches matchn would be replaced with subn.
The argument count limits the maximum number of substitution. If omitted, there's no limit of the work.
With an attribute :icase, character cases are ignored while matching strings.
If block is specified, it would be evaluated with a block parameter |result:string, replaced:boolean|, where result is the result string and replaced indicates if there is any change between the result and its original string. In this case, the block's result would become the function's returned value.
string#right(len?:number):map {block?}Extracts the specified length of string from right of the source string.
If the argument is omitted, it would return whole the source string.
string#split(sep?:string, count?:number):[icase] {block?}
Creates an iterator generating sub strings extracted from the original one separated by a specified string sep. With an attribute :icase, character cases are ignored while finding the separator.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter.. An iterator. This is the default behavior.:xiter.. An iterator that eliminatesnilfrom its elements.:list.. A list.:xlist.. A list that eliminatesnilfrom its elements.:set.. A list that eliminates duplicated values from its elements.:xset.. A list that eliminates duplicated values andnilfrom its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number| where value is the iterated value and idx the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
string#startswith(prefix:string, pos:number => 0):map:[icase,rest]
Returns true if the string starts with prefix.
If attribute :rest is specified, it returns the rest part if the string starts with prefix, or nil otherewise. You can specify a top position for the matching by an argument pos.
With an attribute :icase, character cases are ignored while matching.
string#strip():[both,left,right] {block?}Returns a string that removes space characters on the left, the right or the both sides of the original string.
The following attributes would specify which side of spaces should be removed:
:both.. Removes spaces on both sides. This is the default.:left.. Removes spaces on the left side.:right.. Removes spaces on the right side.
string#template():[lasteol,noindent] {block?}template instance.
string#tosymbol() {block?}string.translator():static:void {block}
Register a procedure evaluated when a string literal appears with a suffix symbol "$", which is meant to translate the string into another language.
The procedure is described in block takes a block parameter |str:string| where str is the original string, and is expected to return a string translated from the original.
string#unescapehtml() {block?}string#upper() {block?}string#width()Returns the width of the string.
This method takes into account the character width based on the specification of East Asian Width. For example, a kanji-character of Japanese occupies two characters in width.
string#zentohan() {block?}5.46suffixmgr Class
5.46.1Overview
The suffixmgr class provides measures to access suffix managers that are responsible to handle suffix symbols appended to number or string literals.
Below is an example to register a suffix X that converts a string into upper case after being appended to a string literal:
suffixmgr(`string).assign(`X) {|body| body.upper()}
You can use that suffix like below:
'hello world'X
5.46.2Constructor
suffixmgr(type:symbol) {block?}Creates a reference to one of two suffix managers, number and string.
- The number suffix manager works with number literals.
- The string suffix manager works with string literals.
Specify the argument type with a symbol `number for a number suffix manager and `string for a string suffix manager.
5.46.3Method
The suffixmgr class has following methods:
suffixmgr#assign(suffix:symbol):void:[overwrite] {block}
Assigns a procedure to a specified symbol in the suffix manager. The procedure is provided by the block that takes a block parameter |value| where value comes from the preceded literal.
An error occurs if the same suffix symbol has already been assigned. Specifying :overwrite attribute will forcibly overwrite an existing assignment.
5.47symbol Class
5.47.1Overview
5.47.2Method
The symbol class has following methods:
symbol#eval(env?:environment)symbol#len()symbol#width()Returns the width of the symbol.
This method takes into account the character width based on the specification of East Asian Width. For example, a kanji-character of Japanese occupies two characters in width.
5.48template Class
5.48.1Overview
5.48.2Cast Operation
A function that expects a template instance in its argument can also take a value of stream as below:
stream.. Creates atemplateinstance by parsing the content of the stream.
As a stream is capable of being casted from string and binary, such values can also be passed to the argument that expects template.
Using the above casting feature, you can call a function f(tmpl:template) that takes a template instance in its argument as below:
f(template(stream('foo.txt'))).. The most explicit way.f(stream('foo.txt')).. Implicit casting: fromstreamtotemplate.f(template('foo.txt')).. Implicit casting: fromstringtostream.f('foo.txt').. Implicit casting: fromstringtostream, then fromstreamtotemplate.
5.48.3Constructor
template(src?:stream:r):map:[lasteol,noindent] {block?}
Creates a template instance.
If the stream src is specified, the instance would be initialized with the parsed result of the script-embedded text from the stream.
Following attributes would customize the parser's behavior:
:lasteol:noindent
5.48.4Method
template#parse(str:string):void:[lasteol,noindent]
Creates a template instance by parsing a script-embedded text in a string.
Following attributes would customize the parser's behavior:
:lasteol:noindent
template#read(src:stream:r):void:[lasteol,noindent]
Creates a template instance by parsing a script-embedded text from a stream.
Following attributes would customize the parser's behavior:
:lasteol:noindent
template#render(dst?:stream:w)Renders stored content to the specified stream.
If the stream is omitted, the function returns the rendered result as a string.
5.48.5Method Called by Template Directive
template#block(symbol:symbol):voidCreates a template block which content is supposed to be replaced by a derived template.
This method is called by template directive ${=block()} during both the initialization and presentation phase of a template process.
- Initialization: Creates a template block from the specified block that is then registered in the current template with the specified symbol.
- Presentation: Evaluates a template block registered with the specified symbol.
Consider an example. Assume that a block associated with symbol `foo is declared in a template file named base.tmpl as below:
[base.tmpl]
Block begins here.
${=block(`foo)}
Content of base.
${end}
Block ends here.
This template renders the following result:
Block begins here.
Content of derived.
Block ends here.
Below is another template named derived.tmpl that devies from base.tmpl and overrides the block `foo.
[derived.tmpl]
${=extends('base.tmpl')}
${=block(`foo)}
Content of derived.
${end}
This template renders the following result:
Block begins here.
Content of derived.
Block ends here.
template#call(symbol:symbol, args*)
Calls a template macro that has been created by directive ${=define}.
This method is called by template directive ${=call()} during the presentation phase of a template process.
Below is an exemple to call a template macro:
${=call(`show_person, 'Harry', 24)}
This method would return nil if a line-break character is rendered at last and would return a null string otherwise.
template#define(symbol:symbol, `args*):void
Creates a template macro from the specified block, which is supposed to be called by ${=call} directive, and associates it with the specified symbol.
This method is called by template directive ${=define()} during the initialization phase of a template process.
Below is an example to create a template macro:
${=define(`show_person, name:string, age:number)}
${name} is ${age} years old.
${end}
template#embed(template:template)Renders the specified template at the current position.
This method is called by template directive ${=embed()} during the presentation phase of a template process.
Below is an example to embed a template file named foo.tmpl.
${=embed('foo.tmpl')}
As the template rendered by this method runs in a different context from the current one, macros and blocks that it defines are not reflected to the current context.
This method would return nil if a line-break character is rendered at last and would return a null string otherwise.
template#extends(template:template):voidDeclares the current template as a derived one from the specified template.
This method is called by template directive ${=extends()} during the initialization phase of a template process.
The directive must appear in a template only once. An error occurs if the current template has already derived from another template.
Below is an example to declare the current template as one derived from base.tmpl.
${=extends('base.tmpl')}
template#super(symbol:symbol):voidEvaluates a template block registered with the specified symbol in a template from which the current template has derived.
This method is called by template directive ${=super()} during the presentation phase of a template process. The directive is intended to be used within a directive ${=block()}.
Consider an example. Assume that a block associated with symbol `foo is declared in a template named base.tmpl as below:
[base.tmpl]
Block begins here.
${=block(`foo)}
Content of base.
${end}
Block ends here.
This template renders the following result:
Block begins here.
Content of derived.
Block ends here.
Below is another template named derived.tmpl that devies from base.tmpl and overrides the block `foo.
[derived.tmpl]
${=extends('base.tmpl')}
${=block(`foo)}
${=super(`foo)}
Content of derived.
${end}
This template renders the following result:
Block begins here.
Content of base.
Content of derived.
Block ends here.
5.49timedelta Class
5.49.1Overview
The timedelta instance provides a time delta information that works with datetime instance. You can shift time information of datetime by applying addition or subtraction of timedelta to it.
5.49.2Property
A timedelta instance has the following properties:
timedelta#days … number [read/write]timedelta#secs … number [read/write]timedelta#usecs … number [read/write]5.49.3Constructor
timedelta(days:number => 0, secs:number => 0, usecs:number => 0):map {block?}5.50uri Class
5.50.1Overview
The uri instance analyzes a URI string and returns each part in it such as the scheme and path. A generic URI has the following format:
scheme:[//[user:password@]host:port]][/]path[?query][#fragment]
5.50.2Property
A uri instance has the following properties:
uri#host … string [read/write]uri#misc … string [read/write]uri#password … string [read/write]uri#port … string [read/write]uri#scheme … string [read/write]uri#urlpath … string [read/write]uri#user … string [read/write]5.50.3Constructor
uri(str?:string):map {block?}
Creates uri instance.
If the argument str is specified, it would be parsed as a URI which is stored in the instance.
If omitted, the instance would be initialized as an empty one.
5.50.4Method
uri#getfragment()uri#getpath()uri#getquery()dict instance that is made from the query part in the URI path.
uri.parsequery(query:string):static:mapdict instance that contains key-value pairs for the query.
5.50.5Cast Operation
A function that expects a uri instance in its argument can also take a value of string that is recognized as a URI string.
With the above casting feature, you can call a function f(uri:uri) that takes a uri instance in its argument as below:
f(uri('http://example.com')).. The most explicit way.f('http://example.com').. Implicit casting: fromstringtouri.
5.51vertex Class
5.51.1Overview
The vertex class provides vertex information that consists of x, y, z and w values.
5.51.2Property
An vertex instance has the following properties:
vertex#x … number [read/write]vertex#y … number [read/write]vertex#z … number [read/write]5.51.3Constructor
vertex(x:number, y:number, z?:number):map {block?}
Creates a vertex instance that has the given coordinates x, y and z. The argument z is optional and set to zero if omitted.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.
5.51.4Method
vertex.cross (v1:vertex, v2:vertex):static:map {block?}v1 and v2 and returns the result as a vertex instance.
vertex.dot(v1:vertex, v2:vertex):static:map {block?}v1 and v2 and returns the result as a number instance.
vertex#list() {block?}
Creates a list that contains coordinate values [x, y, z] of the target vertex.
If block is specified, it would be evaluated with a block parameter |list:list|, where list is the created instance. In this case, the block's result would become the function's returned value.
vertex.normal(v1:vertex, v2:vertex, v3:vertex):static:map:[unit] {block?}
Calculates a normal vector for a face that consists of three vertices given and returns it as a vertex instance.
In default, it returns a vector before being regulated to have a length of one. Specifying the attribute :unit would apply the calculation.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.
vertex#rotate@x(angle:number):[deg] {block?}
Creates a vertex that is rotated from the target vertex around X-axis by the specified angle in radian. It would be rotated in a direction of tilting Y-axis toward Z-axis.
If the attribute :deg is specified, you can specify the angle in degree unit.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.
vertex#rotate@y(angle:number):[deg] {block?}
Creates a vertex that is rotated from the target vertex around Y-axis by the specified angle in radian. It would be rotated in a direction of tilting Z-axis toward X-axis.
If the attribute :deg is specified, you can specify the angle in degree unit.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.
vertex#rotate@z(angle:number):[deg] {block?}
Creates a vertex that is rotated from the target vertex around Z-axis by the specified angle in radian. It would be rotated in a direction of tilting X-axis toward Y-axis.
If the attribute :deg is specified, you can specify the angle in degree unit.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.
vertex#translate(tx:number, ty:number, tz?:number) {block?}
Creates a vertex that is translated from the target vertex by the specified offsets tx, ty and tz.
If block is specified, it would be evaluated with a block parameter |v:vertex|, where v is the created instance. In this case, the block's result would become the function's returned value.