for each (object) in (list)
This construct specifies the actions that must be performed for every element of a collection.
Purpose
You use this construct to apply one or more actions to all objects in a collection.
Syntax
for each <object> [called <variable>,] in <list>:
- <action>*;
Description
The construct for each <object> in <list> is followed by a colon (:) and a list of one or more actions, each on a separate line, each preceded by a dash. End each action statement with a semicolon (;).
The implicit variable this <object> can be used in each action statement within the for each loop to refer to the current object. If you nest a for each statement inside another, you can use the called construct to define an explicit name for the object in the 'outer' for each loop in order to reference it clearly from within the nested for each loop.
Example
The following rule shows how to apply a discount to all the expensive items in a customer’s shopping cart.
when a purchase event occurs, called 'the purchase'
definitions
set 'expensive items' to all items in the items of 'the purchase'
where the price of each item is greater than 100;
then
for each item in the items of 'the purchase':
- emit a new coupon where
the customer is 'the customer',
the discount is 5;
The following rule shows a simple for each action statement with no called construct.
definitions
set 'senior customers' to all customers in the customers of 'the store'
where the age of each customer is more than 75;
then
for each customer in ‘senior customers’:
- emit a new coupon where
the customer is this customer,
the discount is 5;
The following rule shows two nested for each statements. The called construct is used so that each customer can be explicitly referred to from within the nested for each loop.
definitions
set 'senior customers' to all customers in the customers of 'the store'
where the age of each customer is more than 75;
set 'new accounts to all accounts in the accounts of 'the store'
where each account is a new account;
then
for each customer called 'c', in ‘senior customers’:
- for each account in 'new accounts':
- emit a new statement where
the account is this account,
the mailing address is the mailing address of 'c';