Friday, June 4, 2010

Set-Operations

When writing templates it's sometime useful to merge the result of two or more selector expressions and iterate of it. In the older versions there was only one possibility to achieve this, writing your own Java template function. With the new version of actifsource we added three keywords to the selector line syntax. Since the selector line doesn't contain any source code, we don't break the rule of avoiding to mixture of source code and template code.

The three keywords are "union", "intersect", "except". All three are binary operations operating on lists. Additional to the keywords we allow to use round brackets for changing the evaluation order.


The union keyword

The union keywords merges the result of two selector expressions (m1 union m2) by creating a new list containing all elements of m1 and m2. Since we operate on lists this will preserve the order and allows for duplicate elements. As a result we get one big list first containing all element of the result from m1 followed by all element of the result from m2.

For example [1, 2, 3, 5, 4] union [2, 4, 3] will result in [1, 2, 3, 5, 4, 2, 4, 3].


The intersect keyword

The intersect keyword merges the result of two selector (m1 intersect m2) so that all occurrences of an element in m1 that exceed the occurrence of that element in m2 are removed from m1. This keeps the order as in m1 except for the elements removed.

For example [1, 2, 3, 5, 2] intersect [1, 3, 3, 2] will result in [1, 2, 3].


The except keyword

The except keywords merges the result of two selector expressions (m1 except m2) by removing all element of m2 from the result of m1. Since we operate on lists this will preserve the order and elements contained multiple times in the result of m1 will only removed as often they are contained in m2.

For example [1, 2, 3, 5, 2, 4] except [2, 4, 6, 3] will result in [1, 5, 2].


For what can it be used?

When traversing the hierarchy or collecting referenced objects it's often recommended to exclude the own element.

As an example I built a simple model with persons. All person can have friends. If you want to collect the friends of all friends, except the person itself and the friends that are known directly, you can use the following expression:


Or you can collect all friends and include person itself:



With the set operation there are much less situations where you have to write template functions, which makes writing templates much faster and easier.

No comments:

Post a Comment