Top Documents Download Gallery Repository
Are you looking for a Software Engineer? Check Here

5Built-in Class

5.1argument Class

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.1Property

An argument instance has the following properties:

Property Type R/W Explanation
function function R The function instance that has created the argument.
values list R A list of argument values.

5.1.2Method

argument#finalize_trailer
argument#finalize_trailer():void
Signals finalizing status to trailers after the current function.

argument#isset
argument#isset(symbol:symbol)
Returns true if the function is called with an attribute that matches the specified symbol.

argument#quit_trailer
argument#quit_trailer():void
Cancels evaluation of following trailers.

Example:

f(flag:boolean) = {
    !flag && __arg__.quit_trailer() 
}

f(true) println('printed')
f(false) println('not printed')

5.2array Class

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 arrayutil 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 arrayutil module before using the array class in your program.

5.2.1Property

A array instance has the following properties:

Property Type R/W Explanation
T array R Return an array with its row and column being tranposed.
elembytes number R Returns the size of each element in bytes.
elemtype symbol R Returns the typename of the elements as a `symbol` such as `` `boolean``, `` `int8``, `` `uint8``, `` `int16``, `` `uint16``, `` `int32``, `` `uint32``, `` `int64``, `` `uint64``, `` `half``, `` `float``, `` `double`` and `` `complex``.
memoryid string R Returns the id of memory.
ndim number R Returns the number of dimensions.
p pointer R Returns the pointer through which you can inspect and modify the content of the array as a binary data.
shape number R Returns a list of sizes of each dimension.
size number R Returns the total number of elements.

5.2.2Constructor

array
array(src?, elemtype?:symbol) {block?}
Creates an array instance with elements of type double from a list or an iterator specified in the argument src, or elements described in a block. Below are examples:

array([[0, 1, 2], [3, 4, 5]])
array {{0, 1, 2}, {3, 4, 5}}

Specifying the argument elemtype would create an array of other type than double.

Available symbols for elemtype are as follows:

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.identity
array.identity(n:number, elemtype?:symbol):static:map {block?}
Creates an array that represents a identity matrix with specified size n.

Example:

x = array.identity(3)
    // array@double {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}

array.interval
array.interval(begin:number, end:number, samples:number, elemtype?:symbol):static:map:[open,open_l,open_r] {block?}
Creates a one-dimentional array that contains a sequence of numbers by specifying the beginning and ending numbers, and the number of samples between them.

In default, it creates a sequence that contains the beginning and ending numbers. Following attributes would generate the following numbers:

Example:

x = array.interval(0, 3, 7)
    // array@double {0, 0.5, 1, 1.5, 2, 2.5, 3}

array.ones
array.ones(dims[]:number, elemtype?:symbol):static:map {block?}
Creates an array with the specified dimensions, which elements are initialized by one.

Example:

x = array.ones([3, 4])
    // array@double {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}

array.rands
array.rands(dims[]:number, range?:number, elemtype?:symbol):static:map {block?}
Creates an array with the specified dimensions, which contains random numbers.

array.rands@normal
array.rands@normal(dims[]:number, mu?:number, sigma?:number, elemtype?:symbol):static:map {block?}
Creates an array with the specified dimensions, which contains normal distribution random numbers.

array.range
array.range(num:number, num_end?:number, step?:number, elemtype?:symbol):static:map {block?}
Creates an array that contains a sequence of integer numbers.

This function can be called in three formats that generate following numbers:

Example:

x = array.range(5)
    // array@double {0, 1, 2, 3, 4}
x = array.range(2, 5)
    // array@double {2, 3, 4}
x = array.range(2, 10, 2)
    // array@double {2, 4, 6, 8}

array.rotation
array.rotation(angle:number, xtrans?:number, ytrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array that rotates 2-D coords by the specified angle.

The 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 or ytrans is specified, it would create an array that works as translation as well as rotation.

array.rotation@x
array.rotation@x(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array that rotates 3-D coords around x-axis by the specified angle.

The 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 or ztrans is specified, it would create an array that works as translation as well as rotation.

array.rotation@y
array.rotation@y(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array that rotates 3-D coords around y-axis by the specified angle.

The 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 or ztrans is specified, it would create an array that works as translation as well as rotation.

array.rotation@z
array.rotation@z(angle:number, xtrans?:number, ytrans?:number, ztrans?:number, elemtype?:symbol):static:map:[deg] {block?}
Creates an array that rotates 3-D coords around z-axis by the specified angle.

The 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 or ztrans is specified, it would create an array that works as translation as well as rotation.

array.scaling
array.scaling(xscale:number, yscale:number, zscale?:number, elemtype?:symbol):static:map {block?}
Creates an array that scales coords. If the argument zscale is specified, it would create an array that works with 3-D coords. Otherwise, it would create what works with 2-D coord.n

array.translation
array.translation(xtrans:number, ytrans:number, ztrans?:number, elemtype?:symbol):static:map {block?}
Creates an array that translates coords. If the argument ztrans is specified, it would create an array that works with 3-D coords. Otherwise, it would create what works with 2-D coords.n

array.zeros
array.zeros(dims[]:number, elemtype?:symbol):static:map {block?}
Creates an array with the specified dimensions, which elements are initialized by zero.

Example:

x = array.zeros([3, 4])
    // array@double {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}

5.2.3Method

array.dot
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
array#dump(stream?:stream):void:[upper]
Prints out a binary dump of the array's content.

array#each
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:

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
array#elemcast(elemtype:symbol) {block?}
Cast value type of contained elements.

Available symbols for elemtype are as follows:

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
array#fill(value:number):map:void
Fills array with a specified value.

array#flatten
array#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
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
array#invert(eps?:number):map {block?}
Returns an 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#iselemsame(array:array)
Returns true if the target array instance has the same elements with the specified array.

array#issquare
array#issquare()
Returns true if the target array consists square matrices.

array#mean
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#offset
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
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
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
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#sum
array#sum(axis?:number):map {block?}
Calculates a summation value of elements in the target array.

array#tail
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
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.

5.3audio Class

The audio class provides measures to work on audio data.

5.3.1Method

audio#each
audio#each(channel:number, offset?:number):map {block?}

audio#get
audio#get(channel:number, offset:number):map

audio#put
audio#put(channel:number, offset:number, data:number):map:reduce

audio#sinewave
audio#sinewave(channel:number, freq:number, len:number, amplitude?:number):map:reduce

audio#store
audio#store(channel:number, offset:number, data:iterator):reduce

5.4binary Class

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.1Property

A binary instance has the following properties:

.
Property Type R/W Explanation
p pointer R Returns a pointer instance that accesses the binary. This result is equivalent to that of calling the method binary#pointer()
size number R Returns the binary size in bytes.
writable boolean R Indicates if the content of the binary object is writable.

5.4.2Constructor

binary
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.3Method

binary.alloc
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
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
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
binary#reader() {block?}
Creates a 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
binary#writer() {block?}
Creates a 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

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:

Note that the number 0 is treated as true in logical operations.

5.6codec Class

The codec class has features to decoding/encoding character codes stored in string and binary. Following measures are provided:

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:

Importing other codec modules would expand available codecs. You can call codecs.dir() to get a list of codec names currently available.

5.6.1Predefined 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.2Constructor

codec
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.3Method

codec#addcr
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.

codec#decode
codec#decode(buff:binary):map
Decodes a binary buff and returns the decoded result as string.

codec#delcr
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.

codec#encode
codec#encode(str:string):map
Encodes a string str and returns the encoded result as binary.

5.6.4Cast 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:

5.7color Class

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.1Predefined 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.2Property

A color instance has the following properties:

Property Type R/W Explanation
a number R/W Value of the alpha element.
b number R/W Value of the blue element.
g number R/W Value of the green element.
r number R/W Value of the red element.

5.7.3Cast Operation

A function that expects a color instance in its argument can also take a value of symbol, string and list as below:

With the above casting feature, you can call a function f(c:color) that takes a color instance in its argument as below:

5.7.4Constructor

color
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:

5.7.5Method

color#getgray
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
color#html()
Returns a color string in a format of '#rrggbb' that is used in HTML documents.

color#list
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

The complex class provides measures to calculate complex numbers.

You can create a complex instance by following ways:

5.8.1Constructor

complex
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.2Method

complex.polar
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
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

The datetime class provides measures to handle date and time information.

You can create a datetime instance by calling following functions:

You can calculate a datetime with a timedelta to put its date and time values forward and backward.

5.9.1Predefined 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.2Property

A datetime instance has the following properties:

Property Type R/W Explanation
year number R/W Chritian year.
month number R/W Month starting from 1. Numbers from 1 to 12 correspond to January to December.
day number R/W Day in a month starting from 1.
hour number R/W Hour in a day between 0 and 23.
min number R/W Minute in an hour between 0 and 59.
sec number R/W Second in a minute between 0 and 59.
usec number R/W Millisecond in a second between 0 and 999.
wday number R Week number starting from 0. Number from 0 to 6 corresponds to Sunday to Saturday.
week number R Week symbol that takes one of the followings: `sunday, `monday, `tuesday, `wednesday, `thursday, `friday, `saturday
yday number R Day in a year starting from 1.
unixtime number R Seconds passed from 00:00:00 on January 1st in 1970 in UTC.

5.9.3Constructor

datetime
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:

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.4Method

datetime#clrtzoff
datetime#clrtzoff():reduce
Eliminates timezone offset information from the instance.

datetime#format
datetime#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:

Below are the symbols of predefined styles:

datetime.isleap
datetime.isleap(year:number):static:map
Returns true if the specified year is a leap one.

datetime.monthdays
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
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
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:

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
datetime#settzoff(mins:number):reduce
Sets timezone offset in minutes.

datetime.time
datetime.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
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#utc()
Calculates UTC time of the target datetime instance. An error occurs if the instance has no timezone offset

datetime.weekday
datetime.weekday(year:number, month:number, day:number):static:map
Returns a week number for the specified date, which starts from 0 for Sunday.

5.10declaration Class

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:

Below is an example to print argument names declared in a function.

f(a, b, c, d) = {}
println(f.decls:*name)

5.10.1Property

A declaration instance has the following properties:

Property Type R/W Explanation
symbol symbol R The name of the declaration in symbol.
name string R The name of the declaration in string.
default expr R The expression that provides a default value.

5.10.2Method

declaration#istype
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:

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

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:

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.0.1Index 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.1Constructor

dict
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.2Method

dict#append
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:

dict#clear
dict#clear()
Clears all the key-value pairs in the dictionary.

dict#erase
dict#erase(key):map
Erases a key-value pair that mathces the provided key.

The key is either number, string or symbol.

dict#get
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.

dict#haskey
dict#haskey(key):map
Returns true if the specified key exists in the dictionary.

dict#items
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:

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

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#len()
Returns the number of key-value pairs in the dictionary.

dict#put
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:

Another measure to add a key-value pair is to use an index operator. The following two codes have the same effect.

dict#values
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:

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

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.1Constructor

directory
directory(pathname:string):map {block?}
Creates a directory instance from the specified path name.

5.13environment Class

The environment class provides measures to operate variables in an environment, which is a fundamental mechanism to store variables.

5.13.1Method

environment#getprop!
environment#getprop!(symbol:symbol):map

environment#lookup
environment#lookup(symbol:symbol, escalate:boolean => true):map
Looks up a specified symbol in the environment and returns the associated value. In default, if the symbol is not defined in the environment, it will be searched in environments outside of the current one. Set escalate flag to false in order to disable such an escalation behaviour. Returns false when the symbol could not be found.

environment#setprop!
environment#setprop!(symbol:symbol, value):map

5.14error Class

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.1Predefined 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.2Property

An error instance has the following properties:

Property Type R/W Explanation
source string R The name of the file that causes this error.
lineno number R The number of line where the expression that causes this error starts.
linenobtm number R The number of line where the expression that causes this error ends.
postext string R A text that consists of a source name and a line number.
text string R An error message. If an attribute `:lineno` is specified, it would contain a line number.
trace expr[] R Stack trace.

5.15expr Class

The expr class provides inromation about the language's syntax expression.

5.15.1Property

An expr instance has the following properties:

Property Type R/W Explanation
attrfront symbol[] R Exists in "identifier" and "caller".
attrs symbol[] R Exists in "identifier" and "caller".
attrsopt symbol[] R Exists in "identifier" and "caller".
block expr R Exists in "caller".
blockparam iterator R Exists in "block".
body string R Exists in "suffixed".
car expr R Exists in "compound".
cdr iterator R Exists in "compound".
child expr R Exists in "unary".
children iterator R Exists in "collector".
left expr R Exists in "binary".
lineno number R
linenobtm number R
operator operator R Exists in "unaryop", "binaryop" and "assign".
postext string R
right expr R Exists in "binary".
source string R
suffix symbol R Exists in "suffixed".
symbol symbol R Exists in "identifier".
trailer expr R Exists in "caller".
typename string R
typesym symbol R
value any R Exists in "value".

5.15.2Constructor

expr
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.3Method

expr#eval
expr#eval(env?:environment)
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
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
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:

The argument indent specifies a string used for indentation. Its default is a sequence of four spaces.

expr#tofunction
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#unquote()
Returns expr instance that has removed quote operator from the original expr.

expr#write
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:

The argument indent specifies a string used for indentation. Its default is a sequence of four spaces.

expr#isunary
expr#isunary()
Returns true if expr is an expression of unary.

expr#isunaryop
expr#isunaryop()
Returns true if expr is an expression of unaryop.

expr#isquote
expr#isquote()
Returns true if expr is an expression of quote.

expr#isbinary
expr#isbinary()
Returns true if expr is an expression of binary.

expr#isbinaryop
expr#isbinaryop()
Returns true if expr is an expression of binaryop.

expr#isassign
expr#isassign()
Returns true if expr is an expression of assign.

expr#ismember
expr#ismember()
Returns true if expr is an expression of member.

expr#iscollector
expr#iscollector()
Returns true if expr is an expression of collector.

expr#isroot
expr#isroot()
Returns true if expr is an expression of root.

expr#isblock
expr#isblock()
Returns true if expr is an expression of block.

expr#islister
expr#islister()
Returns true if expr is an expression of lister.

expr#isiterer
expr#isiterer()
Returns true if expr is an expression of iterer.

expr#iscompound
expr#iscompound()
Returns true if expr is an expression of compound.

expr#isindexer
expr#isindexer()
Returns true if expr is an expression of indexer.

expr#iscaller
expr#iscaller()
Returns true if expr is an expression of caller.

expr#isvalue
expr#isvalue()
Returns true if expr is an expression of value.

expr#isidentifier
expr#isidentifier()
Returns true if expr is an expression of identifier.

expr#issuffixed
expr#issuffixed()
Returns true if expr is an expression of suffixed.

5.16formatter Class

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.1Method

formatter#getminwidth
formatter#getminwidth()
Returns an expected minimum width for the field.

For example, with '%3d', this method would return 3.

formatter#getpadding
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
formatter#getplusmode()
Returns a symbol that indicates an expected action when a positive number appears.

formatter#getprecision
formatter#getprecision()
Returns an expected precision for the field.

For example, with '%.3d', this method would return 3.

formatter#isleftalign
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
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
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

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.1Property

A function instance has the following properties:

Property Type R/W Explanation
decls iterator R iterator of declaration instances that provide information about argument declaration the function defines.
expr expr R/W an expression of the function.
format string R a string showing a declared format of the function.
fullname string R a full name of the function that is prefixed by a name of the module or the class it belongs to.
name string R a name of the function in string.
symbol symbol R/W a name of the function in symbol.

5.17.2Operator

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.3Constructor

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

5.17.4Method

function.getdecls
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
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
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
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
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
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
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.18help Class

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.18.1Property

A help instance has the following properties:

Property Type R/W Explanation
title string R The title of the help.
format string R A name of the syntax format in which the help text is described such as 'markdown'.
lang symbol R A symbol of the natural language in which the help text is written. For example, `en for English and `ja for Japanese.
text string R The help text.

5.18.2Method

help.text@iterator
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
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
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.19image Class

The image class provides following measures to handle graphic image data:

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.19.1Property

An image instance has the following properties:

Property Type R/W Explanation
format symbol R

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
width number R Image width.
height number R Image height.
palette palette R/W A palette instance associated with this image. If there is no palette associated, this property returns nil.

5.19.2Constructor

image
image(args+):map {block?}
Returns an image instance with specified characteristics. There are three forms to call the function as below:

The argument format specifies what elements are stored in the memory and takes one of the following symbols:

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.19.3Method

image#allocbuff
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:

image#blur
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
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
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:

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
image#delpalette():reduce
Deletes a palette instance that belongs to the image.

This method returns the reference to the target instance itself.

image#extract
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:

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
image#fill(color:color):reduce
Fills the whole image with the specified color.

This method returns the reference to the target instance itself.

image#fillrect
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
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.

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
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
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
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
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
image#putpixel(x:number, y:number, color:color):map:reduce
Puts a color on the specified position.

This method returns the reference to the target instance itself.

image#size
image#size()
Returns the image size as a list [width, height].

image#store
image#store(x:number, y:number, width:number, height:number, element:symbol, src):reduce

image#read
image#read(stream:stream:r, imagetype?:string):map:reduce
Reads 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
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
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
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.

The following attributes are acceptable:

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

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
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
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
image#write(stream:stream:w, imagetype?:string):map:reduce
Writes 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.20list/iterator Class

The list class provides measures to handle a list structure, which stores values on memory that can be accessed by indexer.

The iterator class provides measures to operate an iterator, which iterates values that come from containers and streams.

5.20.1List-specific Features

5.20.1.1Creating List

There are several ways to create a list.

[3, 1, 4, 1, 5, 9]
@{3, 1, 4, 1, 5, 9}

5.20.1.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.20.1.3Function to Create list Instance

list
list(value+)
Creates a new list from given values in its argument list. If a given value is a list or an iteartor, elements it contains are added to the created list.

xlist
xlist(value+)
Creates a new list from given values except for 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
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.

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

5.20.1.4Method Specific to list Class

list#add
list#add(elem+):reduce
Add specified items to the list.

list#append
list#append(elem+):reduce
Adds specified items to the list. If the item is a list or an iterator, each element in such an item is added to the list.

list#clear
list#clear():reduce
Clear the content of the list.

list#combination
list#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:

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
list#erase(idx*:number):reduce
Erases elements at the specified indices.

list#first
list#first()
Returns a first value in the list. An error occurs when the list is empty.

list#get
list#get(index:number):flat:map
Returns a value stored at the specified index in the list. An error occurs when the index is out of range.

list#insert
list#insert(idx:number, elem+):reduce
Insert specified items to the list from the selected index.

list#isempty
list#isempty()
Return true if the list is empty.

list#last
list#last()
Returns a last value in the list. An error occurs when the list is empty.

list#permutation
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:

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
list#put(index:number, value:nomap):map:reduce
Stores a value at the specified index in the list. An error occurs when the index is out of range.

list#shift
list#shift():[raise]
Shifts the elements of the list. If the content of the list is [1, 2, 3, 4], it becomes [2, 3, 4] after calling this method. In default, no error occurs even when the list is empty. To raise an error for executing this method on an empty list, specify :raise attribute.

list#shuffle
list#shuffle():reduce
Shuffle the order of the list content based on random numbers.

list.zip
list.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:

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.20.2Iterator-specific Features

5.20.2.1Function to Create iterator Instance

iterator
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:

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.20.2.2Method Specific to iterator Class

iterator#delay
iterator#delay(delay:number) {block?}
Creates an iterator that returns each element with an interval time specified by the argument delay in seconds.

iterator#finite
iterator#finite():reduce
Marks the iterator as a finite one by clearing its infinite flag.

This method returns the target instance itself.

iterator#infinite
iterator#infinite():reduce
Marks the iterator as an infinite one by setting its infinite flag.

This method returns the target instance itself.

iterator#isinfinite
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#next()
Returns a next element of the iterator. This operation updates the iterator's internal status.

iterator#repeater
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.20.3Method Common to Both list and iterator Classes

iterable#after
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:

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
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#and()
Calculates a logical AND result of all the values in the iterable.

iterable#before
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:

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
iterable#contains(value)
Returns true if the specified value appears in the iterable.

iterable#count
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
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
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:

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

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
iterable#find(criteria?):[index]

iterable#flatten
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:

In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:

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

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

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
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
iterable#joinb()
Joins all the binary values in the iterable and returns the result.

iterable#len
iterable#len()
Returns the length of the iterable.

iterable#map
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:

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
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 attribute is specified:

iterable#mean
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:

iterable#min
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 attribute is specified:

iterable#nilto
iterable#nilto(replace) {block?}
Creates an iterator that converts nil in the source iterable to the specified value.

iterable#offset
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:

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#or()
Calculates a logical OR result of all the values in the iterable.

iterable#pack
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.

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.

Following format character would take no value from the argument list.

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:

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

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
iterable#print(stream?:stream:w):void
Prints elements to the specified stream.

If omitted, they are printed to the standard output.

iterable#printf
iterable#printf(format:string, stream?:stream:w):void
Prints items in the iterable by using the format.

iterable#println
iterable#println(stream?:stream:w):void

iterable#rank
iterable#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:

You can also put a function to the argument directive that takes two arguments x and y and is expected to return numbers below:

When an attribute :stable is specified, the original order shall be kept for elements that are determined as the same.

iterable#reduce
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
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:

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

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

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

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

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

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

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

You can also put a function to the argument directive that takes two arguments x and y and is expected to return numbers below:

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#stddev
iterable#stddev()
Calculates a standard deviation of elements in the iterable.

iterable#sum
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:

iterable#tail
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:

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

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#variance
iterable#variance()
Calculates a variance of elements in the iterable.

iterable#while
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:

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.21memory Class

An instance of the memory class represents a memory that is stored in array instances.

5.21.1Property

A memory instance has the following properties:

.
Property Type R/W Explanation
p pointer R Returns a pointer instance that accesses the memory. This result is equivalent to that of calling the method memory#pointer()
size number R Returns the memory size in bytes.

5.21.2Constructor

memory
memory(bytes:number):map {block?}

5.21.3Method

memory#array@int8
memory#array@int8():map {block?}
Creates an array@int8 instance that accesses the content of the target memory instance.

memory#array@uint8
memory#array@uint8():map {block?}
Creates an array@uint8 instance that accesses the content of the target memory instance.

memory#array@int16
memory#array@int16():map {block?}
Creates an array@int16 instance that accesses the content of the target memory instance.

memory#array@uint16
memory#array@uint16():map {block?}
Creates an array@uint16 instance that accesses the content of the target memory instance.

memory#array@int32
memory#array@int32():map {block?}
Creates an array@int32 instance that accesses the content of the target memory instance.

memory#array@uint32
memory#array@uint32():map {block?}
Creates an array@uint32 instance that accesses the content of the target memory instance.

memory#array@int64
memory#array@int64():map {block?}
Creates an array@int64 instance that accesses the content of the target memory instance.

memory#array@uint64
memory#array@uint64():map {block?}
Creates an array@uint64 instance that accesses the content of the target memory instance.

memory#array@float
memory#array@float():map {block?}
Creates an array@float instance that accesses the content of the target memory instance.

memory#array@double
memory#array@double():map {block?}
Creates an array@double instance that accesses the content of the target memory instance.

memory#dump
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
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.22nil Class

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.23number Class

The number class is a type of number values. A number literal would create a number instance.

5.23.1Method

number.roundoff
number.roundoff(threshold:number => 1e-10)

5.24operator Class

The operator class provides measures to assign operators with a user-defined procedure.

5.24.1Property

An operator instance has the following properties:

Property Type R/W Explanation
symbol symbol R Operator symbol.

5.24.2Constructor

operator
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.24.3Method

operator#assign
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:

They take different format of block parameters as below:

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

5.25palette Class

The palette instance has a set of color instance.

5.25.1Constructor

palette
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:

In the second form, it can take one of the following symbols:

5.25.2Method

palette#each
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:

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
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
palette#shrink():reduce:[align]
Shrinks the size of the palette to a number powered by two that is enough to contain unique entries. The ordef of existing entries will be kept intact.

palette#updateby
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.26pointer Class

The pointer class provides measures to read and write content in a binary and memory instance.

5.26.1Property

A pointer instance has the following properties:

Property Type R/W Explanation
offset number R/W The current offset.
size number R Returns the size of data accessible from the current offset.
size@all number R Returns the entire size of the target binary or memory. This equals to p.offset + p.size where `p` is a `pointer` instance.
target any R An instance that is associated with the pointer. Currently, this can be an instance of `binary` or `memory`.

5.26.2Constructor

pointer
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.26.3Method

pointer#copyfrom
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
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
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
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
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
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:

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

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

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

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

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

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

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

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

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

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
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
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
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
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
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
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
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
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
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
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
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
pointer#head():reduce
Moves the pointer position to the beginning.

This method returns a reference to the target instance itself.

pointer#hex
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:

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

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.

Following format character would take no value from the argument list.

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:

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
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
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
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
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
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
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
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
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
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
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
pointer#reader() {block?}
Creates a 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
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
pointer#tail():reduce
Moves the pointer position to the end.

This method returns a reference to the target instance itself.

pointer#unpack
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.

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.

Following format character would not return any value.

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:

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
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
pointer#writer() {block?}
Creates a 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.26.4Cast 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:

5.27rational Class

The rational class provides measures to handle rational numbers.

You can create a rational instance with following ways:

Below are examples to realize a common fraction two-thirds:

rational(2, 3)
2r / 3
2 / 3r

5.27.1Constructor

rational
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.27.2Method

rational.reduce
rational.reduce()
Reduces the rational number by dividing its numerator and denominator by their GCD.

5.28semaphore Class

5.28.1Constructor

semaphore
semaphore()

5.28.2Method

semaphore#release
semaphore#release()
Releases the owership of the semaphore that is grabbed by semaphore#wait().

semaphore#session
semaphore#session() {block}
Forms a critical session by grabbing the semaphore's ownership, executing the block and releasing that ownership. It internally proccesses the same job as semaphore#wait() and semaphore#release() before and after the block execution

semaphore#wait
semaphore#wait()
Watis for the semaphore being released by other threads, and ghen grabs that ownership.

5.29stream Class

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:

5.29.1Property

A stream instance has the following properties:

Property Type R/W Explanation
stat object R Status of the stream.
name string R Name of the stream.
identifier string R Identifier of the stream.
readable boolean R Indicates whether the stream is readable.
writable boolean R Indicates whether the stream is writable.
codec codec R `codec` instance associated with the stream.

5.29.2Operator

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.29.3Cast Operation

A function that expects a stream instance in its argument can also take a value of string and binary as below:

Using the above casting feature, you can call a function f(stream:stream) that takes a stream instance in its argument as below:

5.29.4Constructor

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

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.29.5Utility Function

readlines
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:

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.29.6Method

stream#addcr
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.

stream#close
stream#close():void
Closes the stream.

stream#compare
stream#compare(stream:stream:r):map
Returns true if there's no difference between the binary sequences of the target stream instance and that of stream in the argument.

stream.copy
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 copying is done by the following process:

  1. Reads data from stream src into a buffer with the size specified by bytesunit.
  2. If block is specified, it would be evaluated with a block parameter |buff:binary| where buff contains the read data. When the block's result is a binary instance, the content would be written to the stream dst. Otherwise, the read data would be written to stream dst.
  3. If block is not specified, the read data would be written to stream dst.
  4. Continues from step 1 to 3 until data from src runs out.

If the attribute :finalize is specified, some finalizing process will be applied at the end such as copying time stamp and attributes.

This has the same feature as stream#copyfrom() and stream#copyto().

stream#copyfrom
stream#copyfrom(src:stream:r, bytesunit:number => 65536):map:reduce:[finalize] {block?}
Copies the content in src to the target stream instance.

The copying is done by the following process:

  1. Reads data from stream src into a buffer with the size specified by bytesunit.
  2. If block is specified, it would be evaluated with a block parameter |buff:binary| where buff contains the read data. When the block's result is a binary instance, the content would be written to the stream dst. Otherwise, the read data would be written to stream dst.
  3. If block is not specified, the read data would be written to stream dst.
  4. Continues from step 1 to 3 until data from src runs out.

If the attribute :finalize is specified, some finalizing process will be applied at the end such as copying time stamp and attributes.

This has the same feature as stream.copy() and stream#copyto().

stream#copyto
stream#copyto(dst:stream:w, bytesunit:number => 65536):map:reduce:[finalize] {block?}
Copies the content in the target stream instance to stream dst.

The copying is done by the following process:

  1. Reads data from stream src into a buffer with the size specified by bytesunit.
  2. If block is specified, it would be evaluated with a block parameter |buff:binary| where buff contains the read data. When the block's result is a binary instance, the content would be written to the stream dst. Otherwise, the read data would be written to stream dst.
  3. If block is not specified, the read data would be written to stream dst.
  4. Continues from step 1 to 3 until data from src runs out.

If the attribute :finalize is specified, some finalizing process will be applied at the end such as copying time stamp and attributes.

This has the same feature as stream.copy() and stream#copyfrom().

stream#delcr
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.

stream#deserialize
stream#deserialize()

stream#flush
stream#flush():void
Flushes cached data to the stream.

stream#peek
stream#peek(bytes?:number)
Reads specified length of data from the stream and returns a binary instance that contains it. This doesn't move the stream's current file position.

stream#print
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
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
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
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
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
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
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:

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

This method returns the target stream instance itself.

stream#serialize
stream#serialize(value):void

stream#setcodec
stream#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#tell()
Returns the current file position at which read/write operation works.

stream#write
stream#write(ptr:pointer, bytes?:number):reduce
Writes binary data pointer by ptr to the stream. The argument bytes limits the number of data that is to be written to the stream.

5.30string Class

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.

'''first line
second line
third line
'''

5.30.1Suffix 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.30.2Method

string#align
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:

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
string.binary() {block?}
Converts the string into binary instance.

string#capitalize
string#capitalize() {block?}
Returns a string that capitalizes the first character.

string#chop
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
string#decodeuri() {block?}
Returns a string in which percent-encoded characters are decoded.

string#each
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:

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

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
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
string.encode(codec:codec) {block?}
Encodes the string with the given codec and return the result as a binary.

string#encodeuri
string#encodeuri() {block?}
Returns a string in which non-URIC characters are percent-encoded.

string#endswith
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
string#escapehtml():[quote] {block?}
Converts some characters into HTML entity symbols. If attribute :quote is specified, a double-quotation character would be converted to an entity symbol """.

string#find
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
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:

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

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
string#format(values*):map
Taking the string instance as a printf-styled formatter string, it converts values into a string depending on formatter specifiers in it.

string#isempty
string#isempty()
Returns true if the string is empty.

string#left
string#left(len?:number):map
Extracts 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#len()
Returns the length of the string in characters.

string#lower
string#lower()
Converts upper-case to lower-case characters.

string#mid
string#mid(pos:number => 0, len?:number):map {block?}
Extracts the specified length of string from the position pos and returns the result.

If an 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
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
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
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
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
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
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
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:

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

string#template
string#template():[lasteol,noindent] {block?}
Parses the content of the string as a text containing embedded scripts and returns a template instance.

string#tosymbol
string#tosymbol() {block?}
Convers the string into a symbol.

string.translator
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
string#unescapehtml() {block?}
Converts escape sequences into readable characters.

string#upper
string#upper() {block?}
Converts lower-case to upper-case characters.

string#width
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
string#zentohan() {block?}
Converts zenkaku to hankaku characters.

5.31suffixmgr Class

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.31.1Constructor

suffixmgr
suffixmgr(type:symbol) {block?}
Creates a reference to one of two suffix managers, number and string.

Specify the argument type with a symbol `number for a number suffix manager and `string for a string suffix manager.

5.31.2Method

suffixmgr#assign
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.32symbol Class

5.32.1Method

symbol#eval
symbol#eval(env?:environment)
Evaluate a symbol object.

5.33template Class

5.33.1Cast Operation

A function that expects a template instance in its argument can also take a value of stream as below:

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:

5.33.2Constructor

template
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:

5.33.3Method

template#parse
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:

template#read
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:

template#render
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.33.4Method Called by Template Directive

template#block
template#block(symbol:symbol):void
Creates 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.

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
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
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#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#extends(template:template):void
Declares 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
template#super(symbol:symbol):void
Evaluates 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.34timedelta Class

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.34.1Property

A timedelta instance has the following properties:

Property Type R/W Explanation
days number R/W Offset of days.
secs number R/W Offset of seconds.
usec number R/W Offset of micro seconds.

5.34.2Constructor

timedelta
timedelta(days:number => 0, secs:number => 0, usecs:number => 0):map {block?}
Returns a timedelta instance with specified values. The instance actually holds properties of days, secs and usecs.

5.35uri Class

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.35.1Property

A uri instance has the following properties:

Property Type R/W Explanation
scheme string R/W Scheme part in the URI.
user string R/W User part in the URI.
password string R/W Password part in the URI.
host string R/W Host part in the URI.
port string R/W Port part in the URI.
urlpath string R/W URL path part in the URI, which contains the path, query and fragment part.
misc string R/W Misc part in the URI.

5.35.2Constructor

uri
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.35.3Method

uri#getfragment
uri#getfragment()
Returns the fragment part contained in the URI path.

uri#getpath
uri#getpath()
Returns the path part contained in the URI path.

uri#getquery
uri#getquery()
Returns a dict instance that is made from the query part in the URI path.

uri.parsequery
uri.parsequery(query:string):static:map
This is a utility function to parse a query string and return a dict instance that contains key-value pairs for the query.

5.35.4Cast 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:

5.36vertex Class

The vertex class provides vertex information that consists of x, y, z and w values.

5.36.1Property

An vertex instance has the following properties:

Property Type R/W Explanation
x number R/W
y number R/W
z number R/W
w number R/W

5.36.2Constructor

vertex
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.36.3Method

vertex.cross
vertex.cross (v1:vertex, v2:vertex):static:map {block?}
Calculates cross product between v1 and v2 and returns the result as a vertex instance.

vertex.dot
vertex.dot(v1:vertex, v2:vertex):static:map {block?}
Calculates dot product between v1 and v2 and returns the result as a number instance.

vertex#list
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
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
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
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
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
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.


Copyright (C) 2011-2017 ypsitau