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

4Built-in Function

4.1Formatting and Printing of Text

format
format(format:string, values*):map
Converts 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
print(values*):map:void
Prints out values to standard output.

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

The flags takes one of the following 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
println(values*):map:void
Prints out values and an end-of-line character to the standard output.

4.2Repetition

cross
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 exprs as arguments and they are counted up from the one on the right side. Iterators and lists are the most popular 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:

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

Block parameter format is |idx:number| where idx indicates an index of the loop.

Example:

Example:

for (ch in ['A', 'B', 'C'], i in 1..4) {
    printf('%s-%d ', ch, i)
}
// prints "A-1 B-2 C-3"

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

Block parameter format is |idx:number| where idx indicates an index of the loop.

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

Block parameter format is |idx:number| where idx indicates an index of the loop.

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

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

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

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 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
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
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
else():trailer {block}
Specify an "else" block within a statement of if-elsif-else or try-catch-else-finally.

end
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
switch() {block}
Form a switch block that contains case() and default() function calls. It calls these functions sequentially and exits the execution when one of the conditions is evaluated as true.

case
case(`cond) {block}
Specify an case block within a switch block. After evaluating an expr object cond, the block shall be executed if it has a value of true.

default
default() {block}
Specify a default block within a switch block. If all the preceding condition of case block are not evaluated as true, this block shall be executed.

return
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
try():leader {block}
Specify a try block of a statement of try-catch-else-finally. It catches signals that occur in the block and executes a corresponding catch() or else() function that follow after it.

catch
catch(errors*:error):leader:trailer {block}
Specify an catch block of a statement of try-catch-else-finally. It can take multiple numbers of arguments of error objects to handle. If there's no error objects specified, it handles all the errors that are not handled in the preceding catch() function calls. Block parameter format: |error:error|error is an error object that contains information of the handled error.

finally
finally():finalizer:trailer {block}

raise
raise(error:error, msg:string => 'error', value?)
Raises an error signal with a specified error object, a message string and an additional value.

4.6Data Converter

chr
chr(code:number):map
Converts a UTF-32 code into a string.

hex
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
int(value):map
Converts a value into an integer number like below:

ord
ord(str:string):map
Converts the first character of a string into a number of UTF-32 code. If the string contains more than one characters, it simply neglects trailing ones.

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

tostring
tostring(value):map
Converts a value into a string.

tosymbol
tosymbol(str:string):map
Converts a string into a symbol.

4.7Class Operations

class
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
classref(type+:expr):map {block?}
Looks up a class by an expression of a type name.

struct
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
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
local(`syms+)
Declares symbols of variable that are supposed to be accessed locally in a block.

locals
locals(module?:module) {block?}
Returns an environment object that belongs to a specified module. If the argument module is omitted, it returns an environment object of the current scope.

outers
outers() {block?}
Returns an environment object that accesses to an outer scope.

public
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
scope(target?) {block}
Evaluates block with a local scope.

4.9Module Operations

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

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
module() {block}
Creates a module that contains functions and variables defined in the block and returns it as a module object. This can be used to realize a namespace.

4.10Value Type Information

isbinary
isbinary(value)
Returns true if the value is an instance of binary, and false otherwise.

isboolean
isboolean(value)
Returns true if the value is an instance of boolean, and false otherwise.

isclass
isclass(value)
Returns true if the value is an instance of class, and false otherwise.

iscomplex
iscomplex(value)
Returns true if the value is an instance of complex, and false otherwise.

isdatetime
isdatetime(value)
Returns true if the value is an instance of datetime, and false otherwise.

isdict
isdict(value)
Returns true if the value is an instance of dict, and false otherwise.

isenvironment
isenvironment(value)
Returns true if the value is an instance of environment, and false otherwise.

iserror
iserror(value)
Returns true if the value is an instance of error, and false otherwise.

isexpr
isexpr(value)
Returns true if the value is an instance of expr, and false otherwise.

isfunction
isfunction(value)
Returns true if the value is an instance of function, and false otherwise.

isiterator
isiterator(value)
Returns true if the value is an instance of iterator, and false otherwise.

islist
islist(value)
Returns true if the value is an instance of list, and false otherwise.

ismodule
ismodule(value)
Returns true if the value is an instance of module, and false otherwise.

isnil
isnil(value)
Returns true if the value is an instance of nil, and false otherwise.

isnumber
isnumber(value)
Returns true if the value is an instance of number, and false otherwise.

isrational
isrational(value)
Returns true if the value is an instance of rational, and false otherwise.

issemaphore
issemaphore(value)
Returns true if the value is an instance of semaphore, and false otherwise.

isstring
isstring(value)
Returns true if the value is an instance of string, and false otherwise.

issymbol
issymbol(value)
Returns true if the value is an instance of symbol, and false otherwise.

istimedelta
istimedelta(value)
Returns true if the value is an instance of timedelta, and false otherwise.

isuri
isuri(value)
Returns true if the value is an instance of uri, and false otherwise.

isdefined
isdefined(`identifier)
Returns true if identifier is defined, and false otherwise.

isinstance
isinstance(value, type+:expr):map
Returns true if value is an instance of type or its descendant, and false otherwise.

istype
istype(value, type+:expr):map
Returns true if value is of the type of type, and false otherwise.

typename
typename(`value)
Returns a type name of the value.

undef
undef(`identifier+):[raise]
Undefines identifier in the current scope.

4.11Data Processing

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

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

If you want to specify a list or an iterator for value1 and value2 as selected values, use cond() function instead.

max
max(values+):map
Returns the maximum value among the given arguments.

min
min(values+):map
Returns the minimum value among the given arguments.

4.12Random

Random numbers are generated using SIMD-oriented Fast Mersenne Twister (SFMT) library.

rand
rand(range?:number) {block?}
Returns a random number between 0 and (range - 1). If argument range is not specified, it generates random numbers in a range of [0, 1).

rand@normal
rand@normal(mu?:number, sigma?:number) {block?}
Returns a normal distribution random number with a mean value of mu and a standard deviation of sigma. The default values for mu and sigma are 0 and 1 respectively.

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

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

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 = randns(100)
// x is an infinite iterator to generates random numbers between 0 and 99

randseed
randseed(seed:number):void
Initializes random seed with a specified number.

4.13Property Listing

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


Copyright (C) 2011-2017 ypsitau