RuLa Functions¶
Definition¶
A RuLa function is essentially an expression that performs a task or calculation and then returns one value. The calculation is defined in the function's body. If parameters (or arguments) are required to perform the calculation, they can be passed to the function in parenthesis.
Functions are useful if a task needs to be performed repeatedly at different places in the configuration. Once defined correctly, a function can be used over and over again without having to thinking about the complicated calculation.
Examples¶
Each function needs a name and a body expression and they can take none as well as one or more parameters.
Without parameters¶
This function returns whatever is stated in its body, in this case 'Hello everybody'.
This function will return the number 6.
With one parameter¶
The number that is passed to this function as a parameter is divided by two and then returned as a result.
So divide_by_two(30) would return 15.
With multiple parameters¶
function introduce(first_name, last_name):
'My name is ' + last_name + ' but you can call me ' + first_name
end
In the case of introduce(James, Bond) this would return the string 'My name is Bond but you can call me James".
Within the function's body, other functions can be used, both functions that already exist in Atfinity or the ones that were defined by the user.
function replace_element(some_list, element_to_replace, replacement):
map(
some_list,
if
CURRENT = number_to_replace then
replacement
else CURRENT
end
)
end
This function uses the map function in its body to replace all occurrences of a specific element in that list with a
specified replacement.
So writing replace_number([8, 5, 8], 8, 0) would return [0, 5, 0].
With an instance as a parameter¶
Info
New in Atfinity 17.
A parameter can also be an instance, which lets you read its fields inside the function.
In a rule that declares p is Person, full_name(p) returns the first and last name of that person.
A function does not know which ontology an instance parameter has, so the fields you read on it are not checked when you save the function. A field that does not exist on the instance you pass in returns unknown instead of an error.
What a function can see¶
Info
New in Atfinity 17.
Inside a function you can use its parameters, the variables the function assigns itself, and the variables of the rule that calls it.
A parameter or a variable assigned inside the function always wins over something of the same name outside it, and it
stops existing once the function returns.
So a rule that sets a to 5 and calls a function whose parameter a is 8 sees 8 inside the function and 5 again
afterwards.