4Built-in Function
4.1Formatting and Printing of Text
format(format:string, values*):map
values
into string depending on formatter specifications in format
and returns the result in string. For a detail information about formatter specications, refer to the document of printf()
function.
print(values*):map:void
values
to standard output.
printf(format:string, values*):map:void
Prints out values
to standard output according to formatter specifiers in format
. The format specifier has a format of %[flags][width][.precision]specifier
.
The specifier
takes one of the following characters:
d
,i
.. decimal integer number with a sign marku
.. decimal integer number wihout a sign markb
.. binary integer number without a sign marko
.. octal integer number without a sign markx
.. hexadecimal integer number in lower character without a sign markX
.. hexadecimal integer number in upper character without a sign marke
.. floating number in exponential formE
.. floating number in exponential form (in upper character)f
.. floating number in decimal formF
.. floating number in decimal form (in upper character)g
.. better form betweene
andf
G
.. better form betweenE
andF
s
.. stringc
.. character
The flags
takes one of the following characters.
+
.. Appends a character "+
" before a positive number.-
.. Adjust a string to left.[SPC]
.. Appends a space character before a positive number.#
.. Appends a prefix before a numbers "0b
" for a binary, "0
" for an octal and "0x
" for a hexadecimal number.0
.. Fills lacking columns with "0
" instead of space characters.
The width
is a decimal number that specifies a minimum character. If the width of the corresponding field is less than this number, the lacking part will be filled with space characters or "0
". If the width is equal to or more than this number, there's nothing to be processed. If an asterisk character "*
" is specified for width
, the minimum character width will be retrieved from the argument list.
The width
it a character width that appears on a console, and it takes into account each character width based on the specification of East Asian Width. This means that a kanji-character occupies two characters in width.
The precision
is a decimal number and has different effects depending on specifier
.
For specifiers that formats integer numbers, it specifies a minimum character width and fills 0
for the lacking column. Format specifiers "%03d
" and "%.3d
" have the same effect. When it works in combination with width
, precision
fills 0
in the lacking space before width
does padding. An example is shown below:
printf('%5.3d', 23) .. prints " 023"
For specifiers e
, f
and g
, it specifies a digit number after a decimal point. Examples are shown below:
printf('%.3f', 1 / 3) .. prints "0.333"
printf('%.5f', 1 / 3) .. prints "0.33333"
It has no effect with other specifiers.
println(values*):map:void
values
and an end-of-line character to the standard output.
4.2Repetition
cross (`expr+) {block}
Executes the block
while evaluating all the combinations of results from expr
that has format "var in iteratable
". You can specify one or more such expr
s as arguments and they are counted up from the one on the right side to the left.
Iterators and lists are the most typical iteratables, but even any objects that are cable of generating iterators can be specified as such.
It returns the last evaluated value in the block as its own result, but, if one of :list
, :xlist
, :set
, :xset
or :iter
is specified, it returns a list or evaluated value or an iterator. The rule is as follows:
:list
.. returns a list of result values:xlist
.. returns a list of result values eliminatingnil
:set
.. returns a list of unique values of results:xset
.. returns a list of unique values of results eliminatingnil
:iter
.. returns an iterator that executes the block:xiter
.. returns an iterator that executes the block, skippingnil
Block parameter format is |idx:number, i0:number, i1:number, ..|
where idx
indicates an index of the whole loop and each of i0
, i1
.. indicates an index of each corresponding iterable.
Example:
cross (ch in ['A', 'B', 'C'], i in 1..4) {
printf('%s-%d ', ch, i)
}
// prints "A-1 A-2 A-3 A-4 B-1 B-2 B-3 B-4 C-1 C-2 C-3 C-4 "
for (`expr+) {block}
Executes the block
while evaulating iteration command expr
that has a format "var in iteratable
". For var
, an identifier or a list of identifiers is specified. For iterable
, you can spedify iterators and lists as well as any objects that are cable of generating iterators.
You can specify one or more expr
in the argument list. In such a case, it continues to repeat until the shortest iterable among them reaches at its end.
It returns the last evaluated value in the block as its own result, but, if one of :list
, :xlist
, :set
, :xset
or :iter
is specified, it returns a list or evaluated value or an iterator. The rule is as follows:
:list
.. returns a list of result values:xlist
.. returns a list of result values eliminatingnil
:set
.. returns a list of unique values of results:xset
.. returns a list of unique values of results eliminatingnil
:iter
.. returns an iterator that executes the block:xiter
.. returns an iterator that executes the block, skippingnil
Block parameter format is |idx:number|
where idx
indicates an index of the loop.
Example:
for (ch in ['A', 'B', 'C'], i in 1..4) {
printf('%s-%d ', ch, i)
}
// prints "A-1 B-2 C-3"
repeat (n?:number) {block}
Executes the block for n
times. If n
is omitted, it repeats the block execution forever.
It returns the last evaluated value in the block as its own result, but, if one of :list
, :xlist
, :set
, :xset
or :iter
is specified, it returns a list or evaluated value or an iterator. The rule is as follows:
:list
.. returns a list of result values:xlist
.. returns a list of result values eliminatingnil
:set
.. returns a list of unique values of results:xset
.. returns a list of unique values of results eliminatingnil
:iter
.. returns an iterator that executes the block:xiter
.. returns an iterator that executes the block, skippingnil
Block parameter format is |idx:number|
where idx
indicates an index of the loop.
while (`cond) {block}
Executes the block while the evaluation result of cond
is true.
It returns the last evaluated value in the block as its own result, but, if one of :list
, :xlist
, :set
, :xset
or :iter
is specified, it returns a list or evaluated value or an iterator. The rule is as follows:
:list
.. returns a list of result values:xlist
.. returns a list of result values eliminatingnil
:set
.. returns a list of unique values of results:xset
.. returns a list of unique values of results eliminatingnil
:iter
.. returns an iterator that executes the block:xiter
.. returns an iterator that executes the block, skippingnil
Block parameter format is |idx:number|
where idx
indicates an index of the loop.
break(value?):symbol_func:void
Exits from an inside of a loop that is formed with repeating functions like repeat()
, while()
, for()
and cross(),
as well as other functions generating an iterator.
After this function is called, the current loop value would be set to value
given in the function's argument. If the argument is omitted, that would be set to nil
.
However, when the loop function is called with one of the attributes, :list
, :xlist
, :set
, :xset
, :iter
and :xiter
, the argument value of break()
is NOT included as an element in the list or iterator.
continue(value?):symbol_func:void
Cancels the current turn of a loop and continues on to the next. This function can be used in a loop that is formed with repeating functions like repeat()
, while()
, for()
and cross()
, as well as other functions generating an iterator.
After this function is called, the current loop value would be set to value
given in the function's argument. If the argument is omitted, that would be set to nil
.
If the loop function is specified with one of the attributes :list
, :xlist
, :set
, :xset
, :iter
and :xiter
, the argument value of continue()
is included as an element in the list or iterator.
4.3Value Generator
consts(value, num?:number) {block?}
Creates an iterator that generates the same value specified by the argument value
.
The argument num
specifies the number of elements to be generated. If omitted, it would generate the value infinitely.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter
.. An iterator. This is the default behavior.:xiter
.. An iterator that eliminatesnil
from its elements.:list
.. A list.:xlist
.. A list that eliminatesnil
from its elements.:set
.. A list that eliminates duplicated values from its elements.:xset
.. A list that eliminates duplicated values andnil
from its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number|
where value
is the iterated value and idx
the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example to create an iterator that returns constant values:
x = consts('hello', 10)
// x generates 'hello' for 10 times
dim(n+:number) {block?}
Returns a list that contains n
values of nil
. If you pass multiple numbers for n
, it would create a nested list.
Below is an example to create a one-dimentional list:
x = dim(3)
// x is [nil, nil, nil]
Below is an example to create a two-dimentional list:
x = dim(3, 2)
// x is [[nil, nil], [nil, nil], [nil, nil]]
The optional block
should return values for each element and takes block parameters: |i0:number, i1:number, ..|
where the arguments i0
and i1
take indices of the loops.
Below is an example to create a one-dimentional list containing a string:
x = dim(3) {'Hi'}
// x is ['Hi', 'Hi', 'Hi']
Below is an example to create a two-dimentional list that consists of strings showing indices.
x = dim(3, 2) {|i, j| format('%d-%d', i, j) }
// x is [['0-0', '0-1'], ['1-0', '1-1'], ['2-0', '2-1']]
interval(begin:number, end:number, samples:number):map:[open,open_l,open_r] {block?}
Creates an iterator that generates 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:
:open
.. Numbers in range of(begin, end)
that doesn't contain eitherbegin
orend
.:open_l
.. Numbers in range of(begin, end]
that doesn't containbegin
.:open_r
.. Numbers in range of[begin, end)
that doesn't containend
.
range(num:number, num_end?:number, step?:number):map {block?}
Creates an iterator that generates a sequence of integer numbers.
This function can be called in three formats that generate following numbers:
range(num)
.. Numbers between0
and(num - 1)
.range(num, num_end)
.. Numbers betweennum
and(num_end - 1)
.range(num, num_end, step)
.. Numbers betweennum
and(num_end - 1)
incremented bystep
.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter
.. An iterator. This is the default behavior.:xiter
.. An iterator that eliminatesnil
from its elements.:list
.. A list.:xlist
.. A list that eliminatesnil
from its elements.:set
.. A list that eliminates duplicated values from its elements.:xset
.. A list that eliminates duplicated values andnil
from its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number|
where value
is the iterated value and idx
the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below are examples:
x = range(10)
// x generates 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
x = range(3, 10)
// x generates 3, 4, 5, 6, 7, 8, 9
x = range(3, 10, 2)
// x generates 3, 5, 7, 9
4.4Branch and Flow Control
if (`cond):leader {block}
Specify an "if" block within a statement of if-elsif-else
.
If the evaluation result of cond
is determined as true, the block would be executed, and its evaluation result would become the returned value of the function.
Otherwise, if the function is followed by a trailer elsif
or else
, that would be evaluated. If no trailer exists, the function returns nil
value.
elsif (`cond):leader:trailer {block}
Specify an "elsif" block within a statement of if-elsif-else
.
If the evaluation result of cond
is determined as true, the block would be executed, and its evaluation result would become the returned value of the function.
Otherwise, if the function is followed by a trailer elsif
or else
, that would be evaluated. If no trailer exists, the function returns nil
value.
else():trailer {block}
if-elsif-else
or try-catch-else-finally
.
end(dummy*):end_marker:symbol_func:trailer:void
Specify an end of a sequence.
This function is supposed to be used as a block terminator in an embedded script of a template.
switch() {block}
case()
and default()
function calls. It calls these functions sequentially and exits the execution when one of the conditions is evaluated as true.
case(`cond) {block}
default() {block}
return(value?):symbol_func:void
Skips the remaining procedure of the current function and returns to the context that calls it.
If it takes an argument, the value is treated as a result of the function. Otherwise, the returned value would be nil
.
4.5Exception Handling
try():leader {block}
catch()
or else()
function that follow after it.
catch(errors*:error):leader:trailer {block}
catch()
function calls. Block parameter format: |error:error|error
is an error object that contains information of the handled error.
finally():finalizer:trailer {block}
raise(error:error, msg:string => 'error', value?)
4.6Data Converter
chr(code:number):map
hex(num:number, digits?:number):map:[upper]
Converts a number into a hexadecimal string. Argument digits
specifies a minimum columns of the converted result and fills 0
in the lacking space.
In default, it uses lower-case characters in its conversion, while it uses upper-case ones when :upper
attribute is specified.
int(value):map
Converts a value into an integer number like below:
- For a number value, it would be converted into an integer number.
- For a compex value, its absolute number would be converted into an integer number.
- For a string value, it would be parsed as an integer number. An error occurs if it has an invalid format.
- For other values, an error occurs.
ord(str:string):map
tonumber(value):map:[nil,raise,strict,zero]
Converts a string value into a number by a lexical parsing. If the value is not a string, it first tries to convert the value into a string.
If the string starts with a sequence of characters that can be parsed as a number literal, it's not a failure even when it contains other characters following them. Specifying an attribute :strict
doesn't allow such a case and fails the process.
If it fails the conversion, it would return nil
value. Attributes described below are prepared to customize the behaviour in the case of a failure.
:raise
.. raises an error:zero
.. returns zero value:nil
.. returnsnil
value (default)
tostring(value):map
tosymbol(str:string):map
4.7Class Operations
class(superclass?:class) {block?}
Creates a class
that includes methods and properties described in the content of the block
. The detail information on how to describe the block content for this function is written in "Gura Language Manual".
Below is an example to create a class named Person
:
Person = class {
__init__(name:string, age:number) = {
this.name = name
this.age = age
}
Print() = {
printf('name:%s age:%d\n', this.name, this.age)
}
}
person = Person('Smith', 26)
person.Print()
If the argument superclass
, which is expected to be a constructor function of a super class, is specified, the created class would inherit methods and properties from the specified class.
classref(type+:expr):map {block?}
struct(`args+):nonamed:[loose] {block?}
Creates a class
for a structure that contains properties specified by args
. It can optionally take a block which declares methods and properties just like class()
function does.
An element in args
is an expression that has the same format with one in the argument list of a function's declaration. Each variable name becomes a member name in the created instance.
Below is an example to create a structure named Person
:
Person = struct(name:string, age:number)
person = Person('Smith', 26)
printf('name:%s age:%d\n', person.name, person.age)
If :loose
attribute is speicied, the generated constructor would take all the arguments as optional. Omitted variables are set to nil
super(obj):map {block?}
Returns a reference to obj
through which you can call methods of the super class.
Example:
A = class {
func() = {}
}
B = class(A) {
func() = {}
}
b = B()
b.func() // B#func() is called.
super(b).func() // A#func() is called.
4.8Scope Operations
local(`syms+)
locals(module?:module) {block?}
module
is omitted, it returns an environment
object of the current scope.
outers() {block?}
public():void {block}
Declares symbols as public ones that are accessible from outer scopes.
If you want to make foo
and bar
accessible, call this function like below:
public { foo, bar }
scope(target?) {block}
4.9Module Operations
import(`module, `alias?):[binary,mixin_type,overwrite] {block?}
Imports a module and creates a variable that represents the imported module. It also returns a value that is a reference to the module.
It searches module files in directories specified by a variable sys.path
.
There are three format to call this function like follow:
import(foo)
.. importsfoo
module and creates a module object namedfoo
import(foo, bar)
.. importsfoo
module and creates a module object namedbar
import(foo) {symbol1, symbol2, symbol3}
.. importsfoo
and mixes up the module's propertiessymbol1
,symbol2
andsymbol3
in the current scope.
In the third format, you can specify an asterisk character to mixes up all the symbols defined in the module like below:
import(foo) {*}
If a specified symbol conflicts with what already exists in the current scope, it will cause an error. Specifying the attribute :overwrite
will avoid such an error and allow overwriting of symbols.
If the argument module
is prefixed by a minus operator like -foo
, it will not create a variable that represents the imported module.
If the argument module
is prefixed by an and operator like &foo
, the trailing expression will be evaluated and its result, which must be a string, is treated as a module name to be imported. Below is a sample to import foo
module through a variable that contains that name:
var = 'foo'
import(&var)
module() {block}
4.10Value Type Information
isbinary(value)
true
if the value
is an instance of binary
, and false
otherwise.
isboolean(value)
true
if the value
is an instance of boolean
, and false
otherwise.
isclass(value)
true
if the value
is an instance of class
, and false
otherwise.
iscomplex(value)
true
if the value
is an instance of complex
, and false
otherwise.
isdatetime(value)
true
if the value
is an instance of datetime
, and false
otherwise.
isdict(value)
true
if the value
is an instance of dict
, and false
otherwise.
isenvironment(value)
true
if the value
is an instance of environment
, and false
otherwise.
iserror(value)
true
if the value
is an instance of error
, and false
otherwise.
isexpr(value)
true
if the value
is an instance of expr
, and false
otherwise.
isfunction(value)
true
if the value
is an instance of function
, and false
otherwise.
isiterator(value)
true
if the value
is an instance of iterator
, and false
otherwise.
islist(value)
true
if the value
is an instance of list
, and false
otherwise.
ismodule(value)
true
if the value
is an instance of module
, and false
otherwise.
isnil(value)
true
if the value
is an instance of nil
, and false
otherwise.
isnumber(value)
true
if the value
is an instance of number
, and false
otherwise.
isrational(value)
true
if the value
is an instance of rational
, and false
otherwise.
issemaphore(value)
true
if the value
is an instance of semaphore
, and false
otherwise.
isstring(value)
true
if the value
is an instance of string
, and false
otherwise.
issymbol(value)
true
if the value
is an instance of symbol
, and false
otherwise.
istimedelta(value)
true
if the value
is an instance of timedelta
, and false
otherwise.
isuri(value)
true
if the value
is an instance of uri
, and false
otherwise.
isdefined(`identifier)
true
if identifier
is defined, and false
otherwise.
isinstance(value, type+:expr):map
true
if value
is an instance of type
or its descendant, and false
otherwise.
istype(value, type+:expr):map
true
if value
is of the type of type
, and false
otherwise.
typename(`value)
undef(`identifier+):[raise]
identifier
in the current scope.
4.11Data Processing
choose(index:number, values+):map
Picks up a value placed at index
in the argument list values
.
Sample:
choose(0, 'apple', 'orange', 'banana') // returns 'apple'
choose(2, 'apple', 'orange', 'banana') // returns 'banana'
cond(flag:boolean, value1:nomap, value2?:nomap):map
Returns value1
if flag
is determined as true, and value2
otherwise. If the argument value2
is omitted, it will return nil
when flag
is determined as false.
This function behaves in a similar way with if
function when it's called like below:
if (flag) { value1 } else { value2 }
Notice that they have the following differences:
- Function
cond()
always evaluates argumentsvalue1
andvalue2
no matter whatflag
value is, while functionif()
doesn't evaluatevalue1
expression whenflag
is determined asfalse
. - Function
cond()
works with implicit mapping, which means that the argumentflag
may be a list or an iterator that are to be processed with the implicit mapping.
The arguments value1
and value2
are not processed by the implicit mapping, so you can specify a list or an iterator for them as selected items.
conds(flag:boolean, value1, value2?):map
Returns value1
if flag
is determined as true, and value2
otherwise. If argument value2
is omitted, it will return nil
when flag
is determined as false.
This function behaves in a similar way with if
function when it's called like below:
if (flag) { value1 } else { value2 }
Notice that they have the following differences:
- Function
conds()
always evaluates argumentsvalue1
andvalue2
no matter whatflag
value is, while functionif()
doesn't evaluatevalue1
expression whenflag
is determined as false. - Function
conds()
works with implicit mapping, which means that the argumentsflag
,value1
andvalue2
may be lists or iterators that are to be processed with the implicig mapping.
If you want to specify a list or an iterator for value1
and value2
as selected values, use cond()
function instead.
max(values+):map
min(values+):map
4.12Random
Random numbers are generated using SIMD-oriented Fast Mersenne Twister (SFMT) library.
rand(range?:number) {block?}
0
and (range - 1)
. If argument range
is not specified, it generates random numbers in a range of [0, 1).
rand@normal(mu?:number, sigma?:number) {block?}
mu
and a standard deviation of sigma
. The default values for mu
and sigma
are 0
and 1
respectively.
rands(range?:number, num?:number) {block?}
Creates an iterator that returns random numbers between 0
and (range - 1)
.
If argument range
is not specified, it generates random numbers in a range of [0, 1).
In default, the created iterator infinitely generates random numbers. The argument num
specifies how many elements should be generated.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter
.. An iterator. This is the default behavior.:xiter
.. An iterator that eliminatesnil
from its elements.:list
.. A list.:xlist
.. A list that eliminatesnil
from its elements.:set
.. A list that eliminates duplicated values from its elements.:xset
.. A list that eliminates duplicated values andnil
from its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number|
where value
is the iterated value and idx
the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
Below is an example to create a create that generates random numbers:
x = rands(100)
// x is an infinite iterator to generates random numbers between 0 and 99
rands@normal(mu?:number, sigma?:number, num?:number) {block?}
Creates an iterator that returns normal distribution random numbers with a mean value of mu
and a standard deviation of sigma
. The default values for mu
and sigma
are 0
and 1
respectively.
If argument range
is not specified, it generates random numbers in a range of [0, 1).
In default, the created iterator infinitely generates random numbers. The argument num
specifies how many elements should be generated.
In default, this returns an iterator as its result value. Specifying the following attributes would customize the returned value:
:iter
.. An iterator. This is the default behavior.:xiter
.. An iterator that eliminatesnil
from its elements.:list
.. A list.:xlist
.. A list that eliminatesnil
from its elements.:set
.. A list that eliminates duplicated values from its elements.:xset
.. A list that eliminates duplicated values andnil
from its elements.
See the chapter of Mapping Process in Gura Language Manual for the detail.
If a block is specified, it would be evaluated repeatingly with block parameters |value, idx:number|
where value
is the iterated value and idx
the loop index starting from zero. In this case, the last evaluated value of the block would be the result value. If one of the attributes listed above is specified, an iterator or a list of the evaluated value would be returned.
randseed(seed:number):void
4.13Property Listing
dir(obj?):[noesc]
Returns a symbol list of variables and functions that are assigned in the environment of obj
.
In default, when the obj
is an instance of a class, it also searches symbols assigned in the class that it belongs to and its parent classes. Specifying attribute :noesc
avoids that behavior.
dirtype(obj?):[noesc]
Returns a symbol list of value types that are assigned in the environment of obj
.
In default, when the obj
is an instance of a class, it also searches symbols assigned in the class that it belongs to and its parent classes. Specifying attribute :noesc
inhibits avoids behavior.