Reflex Builtin Functions - RapturePlatform/Rapture GitHub Wiki

Reflex has a large number of built-in functions that extend the power of the language in a more native way. The println function was introduced earlier. This section describes all of the built-in functions in Reflex.

println

println( expression )

The println function prints to the registered output handler the single parameter passed, which is coerced to a string type if it is not already. In most implementations of Reflex the output handler is wired to be either standard out (the console), the Eclipse console window or the standard log file.

// Println example
println("Hello, world!");
println(5);
println({}); // Prints an empty map
println("one two " + 3);

print

print( expression )

The print function is identical to println except that it does not automatically terminate the output with a carriage return.

// Print example
print("Hello, world!");
print(" And this would be on the same line.");
println(""); // And now force a carriage return
print('\n'); // Or do it this way

typeof

typeof( expression )

The typeof function can be used to determine the type of an expression, which can be a variable identifier as well. The return from the typeof function is a string, which can take the values in the table below.

Internal Type Return Value
String "string"
Number "number"
Boolean "bool"
List "list"
Map "map"
Date "date"
Time "time"
File "file"
No value "void"
Null value "null"
All else "object"

An example of the use of typeof function is shown below:

// typeof example
a = "This is a string";

if typeof(a) == "string" do
   println("Yes, 'a' is a string");
end

assert

assert( boolean-expression )

The assert function is used to test its single parameter for truth. If the expression does not evaluate to true the Reflex script will abort abnormally.

// assert example

assert(true);
assert(typeof(" ") == "string");

size

size( list-expression | string-expression )

The size function returns the size of its single parameter. It is only applicable for strings and lists. For a string the size is the length of the string, for a list it is the size of the list (the number of elements in the list). For convenience, size(null) evaluates to zero.

// size example
a = [1,2,3,4];

if sizeof(a) == 4 do
   println("Yes, that list has four elements");
end

keys

keys( map-expression )

The keys function takes a single map parameter, and returns a list of strings that corresponds to the keys of the associative map. It is useful when you need to iterate over a map.

// keys example

a = { 'one' : 1, 'two' : 2 };
b = keys(a);

for k in b do
   println("Key = " + k + ", value is " + b[k]);
end

debug

debug( expression )

The debug function works in a similar way to the println function, except that the output is sent to any attached debugger instead of to the console. In some Reflex installations this will mean the same thing.

// debug example

println("This will appear in one place");
debug("This will appear in the debugger");

date

date( )
date( string-expression )

The date function returns a date object. If called with zero parameters the object will be initialized to the current date. It can also take a single string parameter which must be a date formatted as "yyyyMMdd". The date object will be initialized to the date represented by that string.

today = date();
aRealDate = date('20120101');

println("Today is " + today + ", today is fun");
println("The start of the year 2012 is " + aRealDate);

time

time( )
time( string-expession )

The time function returns a time object. If called with zero parameters the object will be initialized to the current time. It can also take a single string parameter which must be a time formatted as "HH:mm:ss". The time object will be initialized to the time represented by that string.

// time example

now = time();
then = time('11:00:01');

println("What time is now? " + now);

readdir

readdir( string-expression | file-expression)

The readdir function returns the contents of a directory as a list of file values, although its behavior is really determined by the IO handler installed in the Reflex environment. The function accepts either a string (which corresponds to the name of a folder available to the handler) or a file (returned by the file function or a different call to readdir).

// readdir example
// Recursively look for folders

def readFolder(folder)
    println("Looking at " + folder);
    filesAndFolders = readdir(folder);
    for fAndF in filesAndFolders do
       if isfolder(fAndF) do
          readFolder(fAndF);
       end
    end
end

readFolder('/tmp');

This example starts with the /tmp folder and enumerates all folders below that recursively, printing out the name of each folder found.

isfile

isfile( string-expression | file-expression )

The isfile function evaluates its single argument (which needs to be a file or a string) and returns a boolean indicating whether the argument is actually a file.

// isfile example

const name = '/tmp';

if isfile(name) do
   println(name + " is a file!");
else do
   println(name + " is not a file!");
end

isfolder

isfolder( string-expession | file-expression)

The isfolder function evaluates its single argument (which needs to be a file or a string) and returns a boolean indicating whether the argument is actually a folder.

// isfolder example

const name = '/tmp/out.log';

if isfolder(name) do
   println(name + " is a folder!");
else do
   println(name + " is not a folder!");
end

file

file( string-expression )

The file function creates a Reflex file object from a string, where the string is assumed to be an absolute reference to a real file or folder. Files can be read by the pull operator (<--$) and written to by the push operator ($-->$).

// file example

a = "/tmp/test.txt";
data = "This is some text\n";

aFile = file(a);

data --> aFile;

b = "/tmp/test.txt";
bFile = file(b);

data2 <-- bFile;

assert(data == data2);

delete

delete(file or string expression);

The delete function either attempts to remove a file from the file system (if supported) or removes a document from a repository.

a = "/tmp/test.txt";
data = "This is some text\n";

aFile = file(a);

data --> aFile;
assert(isFile(aFile));

delete(aFile);
assert(!isFile(aFile));

difference

difference(list1, list2)

The difference function compares two lists and returns the elements that are not in both of them.

a = [1,2,3];
b = [3,4,5];

diff = difference(a,b);

println("diff is " + diff);
// Returns 1,2,4,5

The function works on lists of numbers or lists of strings.

unique

unique(list1, list2)

The unique function compares two lists and returns only those elements that are not in common between the lists.

a = [1,2,3];
b = [3,4,5];

un = unique(a,b);

println("unique is " + un);
// Returns 1,2,4,5

The function works on lists of numbers or lists of strings.

json

json( map-expression )

The json function converts a map into a JSON formatted string that represents the contents of that map.

// json example
a = { 'one' : 1, 'two' : 2 };

a1 = "" + a;
a2 = json(a);

assert(a1 == '{ one=1, two=2 }';
assert(a2 == '{ "one" : 1, "two" : 2 }';

Note that the default "string" representation of a map is not a json document, you must call the json function for this.

fromjson

map = fromjson( string-expression )

The fromjson function is the reverse of the json function. It takes a JSON formatted string and converts it to an associative map object.

// fromjson example
a = '{ "alpha" : 1, "beta", 2 };

b = fromjson(a);

assert(b['alpha'] == 1);

md5

string = md5(string-value);

The md5 function returns a string that is an md5 hash of its passed string parameter. As elements in Rapture such as passwords are never passed in none-hashed form, this function is useful in computing values that should be passed over an insecure link.

toHash = "password";
hash = md5(toHash);

println("Hash of " + toHash + " is " + hash);

uuid

string = uuid( )

The uuid function generates a new unique string that can be used as a unique id.

// uuid example
a = uuid();
b = uuid();

assert(a != b);

println(a + " is not the same as " + b);

wait

wait( string )
wait( string, int, int )
wait( process )

The wait function is a convenience function that waits for a document to exist in Rapture. The document name is provided in the first parameter and the optional second and third parameters control the retry interval (wait between checks) and retry count (how many times to check). The return value for the function is either the contents of the document (as a map) or null (if the document did not exist after the interval requested).

Finally, wait can also be used to wait on a process object returned by the spawn command.

// wait example

displayName = '//test/official/config/testData';

// Assume the above does not exist at the moment.

result = wait(displayName);

assert(result == null);

value = {};
value --> displayName;

result = wait(displayName);

assert(result == {});

chain

result = chain( string-expression )
result = chain( string-expression, map-expression )

The chain function is a way of executing a second script in Reflex from a first script. The script is provided as the first string argument and can be passed in an optional parameter map as the second argument. The return value from chain is the return value from the called script.

// chain example
a = "println('The parameter is ' + p); return true;";

res = chain(a, { 'p' : 42 });

println(The result is " + res);

The output from executing the script above would be:

The parameter is 42
The result is true

signal

signal( string-expression, map-expression )

The signal function is the mirror of the wait function in Reflex. The signal+ function creates a document in Rapture with the given displayname and value. It's really a synonym for value --> displayName +.

// signal example

signal('//test/official/config/doc', { 'hello' : 1 });

assert(wait('test/official/config/doc') == { 'hello' : 1 });

sleep

sleep( int-expression )

The sleep function pauses the Reflex script for the number of milliseconds specified in the passed parameter.

// sleep example

for x = 0 to 10 do
   sleep(100);
   if null != wait('test/official/config/doc') do
    x = 10;
   end
end

rand

rand( number-expession )

The rand function returns an integer number between 0 and the passed parameter.

values = [];
for i = 1 to 10 do
   values = values + rand(10);
end

println("Here is a list of random numbers - " + values);

spawn

spawn( list-expression )
spawn( list-expression, map-expression, file-expression)

The spawn command, where supported, provides a mechanism for spawning a child process. The return value is a special process object that can be used in a pull context (to retrieve the standard output from the process) and by the wait function to wait for it to finish.

The first parameter to the spawn command is a list of parameters to pass to the process. The first member of this list is the process to execute, the rest are parameters to pass to this process.

The second parameter is a map expression that defines the environment of the process.

The third parameter is a file object that defines the folder the process should be run in.

env = { "PATH" : "/bin" };
folder = file('/tmp');
program = [ '/bin/ls' , '-l' ];

p = spawn(program, env, folder);
wait(p);

out <-- p;

println("output from process is " + out);

defined

boolean = defined( identifier )

The defined function returns true if the variable identifier passed in is known to Reflex at this point.

a = "This is a string";

assert(defined(a) == true);
assert(defined(b) == false);

round

integer = round( number-expression )

The round function takes a floating point number argument and returns an integer result that is the closest integer to that value.

a = 1.23;
b = 1.56;

assert(round(a) == 1);
assert(round(b) == 2);

lib

Library = lib( string-expression )

Reflex has the ability to embed 3rd party code within the language. The definition of how to do this is defined in a later section, but the lib command is the way a 3rd party library is linked in with Reflex. The string parameter to the lib function is the name of a loadable class that implements the IReflexLibrary interface.

The return value from this function is a special library object that can be used in the call function.

mylib = lib('rapture.addins.BloombergData');

template

result = template(string-expression, map-expression)

The template function takes a string "template" and applies parameters to that template to generate a resulting string where the variables in the template have been replaced with the value of the parameters. Internally Reflex uses the popular stringtemplate library for this task.

tmp = 'Hello <what>';
param = { 'what' : 'world' };

val = template(tmp, param);

println(val);

assert(val == 'Hello world');

Note that an alternative to this approach is to use quoted strings, e.g.

what = 'world';
val = "Hello, ${what}";
println(val);
assert(val == 'Hello world');

cast

value = cast ( expression, string-expression )

The cast function attempts to coerce an expression into either a string or a number. When coercing to a string, a simple "toString" operator is called on the underlying data type. When converting to a number the "toString" value of the expression is passed into a number parser to attempt to convert it to the internal Reflex number type.

a = "1.0";
b = cast(a, "number");
assert(a == 1.0);

y = 1.0;
z = cast(y, "string");
assert(z == '1.0');

merge

value = merge(map-expression, map-expression, ...)

The merge function merges map variables together in Reflex. The rules are that the right hand side of the merge operation will always "win" in such a merge, so that if a key is present in the left hand side and the right hand size it will be the value of the right hand side that will contain the new value. The merge is recursive if the values being merged within the maps are themselves maps -- each lower level map is merged separately.

a = { 'one' : 1 };
b = { 'two' : 2 };
c = merge(a, b);
assert(c == { 'one' : 1, 'two' : 2 });

a = { 'one' : 1 };
b = { 'one' : 'un' };
c = merge(a, b);
assert(c == { 'one' : 'un' });

a = { 'inner' : { 'one' : 1 }};
b = { 'inner' : { 'two' : 2 }};
c = merge(a,b);
assert(c == { 'inner' : { 'one' : 1, 'two' : 2 }});

Merge can take any number of arguments. The first argument is merged with an empty map, which is then merged with the next parameter and so on. The return value is the merged value, the parameters are unchanged by this function.

mergeif

value = mergeif(map-expression, map-expression, ...)

The mergeif function works in a very similar way to the merge function, except that it will not overwrite an existing value. If the same key exists in both maps and the values associated with those keys are also maps then it will also perform a recursive mergeif+ on those lower level maps.

a = { 'one' : 1 };
b = { 'two' : 2 };
c = mergeif(a, b);
assert(c == { 'one' : 1, 'two' : 2 });

a = { 'one' : 1 };
b = { 'one' : 'un' };
c = mergeif(a, b);
assert(c == { 'one' : '1' });

archive

value = archive( string-expression )

The archive command is used to create a special type of file object that tracks a ZIP archive. You can interact with the object in either read mode or write mode.

write mode

In write mode you use the push operator (-->) to send either a simple map to an entry in the file or a two element list - the first element being the name of the entry and the second element being the map data.

After all of the data has been "pushed" to the zip archive the file should be closed through the close function call.

A typical use of an archive is shown in the listing below:

arcFile = archive("test.zip");

dataEntry1 = { "dataField1" : 42, "data2" : "A string" };
dataEntry2 = { "dataField1" : 34, "data3" : "A different string"};

dataEntry1 --> arcFile;
["DataEntryTwo", dataEntry2 ] --> arcFile;

close(arcFile);

In this example we create a zip file with two "files" - the first "file" has a default name and the value of the variable dataEntry1. The second entry has the name "DataEntryTwo" with the value of the variable dataEntry2. The archive+ command is useful for creating backups of large amounts of Rapture data.

read mode

In read mode you use the pull operator (<--) to retrieve data from the zip file, in the same order you pushed it on. The returned value is a map with two entries - a data entry contains the value of this file (its contents as a map) and the displayName entry contains the name of the entry. Reading the archive generated in the listing above is show in the example below:

arcFile = archive("test.zip");

dataRecord1 <-- arcFile;
dataRecord2 <-- arcFile;

close(arcFile);

println("First record data is " + dataRecord1['data']);
println("Second record data is " + dataRecord2['data']);

Back to Overview

⚠️ **GitHub.com Fallback** ⚠️