9 Folding
Ptolemy II supports a fold function, which can be used to program a loop in an expression. The fold function is invoked in the form of fold(f, x, l), where f is a function itself, x is the starting value, and l is a collection of values.The pseudocode for computing the result of the fold function fold(f, x, l) is as follows:
- f must take two arguments. x must be valid as the first argument, and any element in collection l must be valid as the second argument. Moreover, the return value of f must also be valid as the first argument.
- x is the starting value used to invoke f the first time by the fold function. It can be in any type supported by Ptolemy II.
- l must be either an array in the form of "{1, 2, 3, ...}," or a Java collection obtained from a Java method call such as "C.output.connectedPortList()" (assuming C is a Const actor here).
Examples:
- let y = x
- for each element e in l
- let y = f(y, e)
- return y
- fold(
function(x : int, e : int) x + 1,
0, {1, 2, 3}
) This computes the length of array {1, 2, 3}. The result is 3, which is equal to {1, 2, 3}.length(). Function f here is defined with anonymous function function(x : int, e : int) x + 1. Given x and arbitrary element e, it returns x + 1. It is invoked the number of times equal to the number of elements in array {1, 2, 3}. Therefore, x is increased 3 times from the starting value 0.- fold(
function(x : int, e : int) x + e,
0, {1, 2, 3}
) This computes the sum of all elements in array {1, 2, 3}.- fold(
function(x : arrayType(int), e : int)
e % 2 == 0 ? x : x.append({e}),
{}, {1, 2, 3, 4, 5}
) This computes a subarray of array {1, 2, 3, 4, 5} that contains only odd numbers. The result is {1, 3, 5}.- Let C be an actor. fold(
function(list : arrayType(string),
port : object("ptolemy.kernel.Port"))
port.connectedPortList().isEmpty() ?
list.append({port}) : list,
{}, C.portList()
) This returns a list of C's ports that are not connected to any other port (with connectedPortList() being empty). Each port in the returned list is encapsulated in an ObjectToken.