Sunday, July 25, 2010

Group Objects Example

Let's consider the use of group objects.

In the next example I will demonstrate how to extend and customize code using branch-free self modifying code.
(Note that 'project' should be replaced with a name of the source file)

// --- namespace shortcuts ---
#define basic'* = std'basic'*.
#define ctrl'* = std'patterns'*.
#define list'* = std'collections'*.

#symbol Printing = anItem =>
[
// prints a parameter
'program'output << eshownext =" anItem">
[
// replace itself with ESkipNext
#inline elena'172 (self, $self, project'ESkipNext).
].

#symbol ESkipNext = anItem =>
[
// redirects the call to the next group item
$next proceed:anItem.

// replace itself with EShowNext
#inline elena'172 (self, $self, EShowNext).
].

#symbol Program =>
[
#var aList := list'List.
aList += 1 += 2 += 3 += 4 += 5 += 6.

// extending
'program'output << "All items:%n".
#group(ctrl'EEnum, aList) run:Printing.

// customizing
'program'output << "Every second item (1,3,...):%n".
#group(ctrl'EEnum, aList) run:#group(ESkipNext, Printing).

'program'output << "Every second item (2,4,...):%n".
#group(ctrl'EEnum, aList) run:#group(EShowNext, Printing).
].

The program start in Program symbol. Firstly we have to create a collection.

#var aList := list'List.
aList += 1 += 2 += 3 += 4.

In the code below we will enumerate every member of the collection and print it.

// extending
'program'output << "All items:%n".
#group(ctrl'EEnum, aList) run:Printing.

aList is extended with ctrl'EEnum adapter. EEnum is a FOR EACH pattern, executing the action for every member of the collection it is combined with. Printing is a simple action which prints a provided parameter. In combination this code prints every member of the collection.

Let's consider how could we customize it to print only every second item without if statement.

// customizing
'program'output << "Every second item (1,3,...):%n".
#group(ctrl'EEnum, aList) run:#group(ESkipNext, Printing).

Printing action is combined with a special adapter ESkipNext. ESkipNect redirects the flow to the next group item and modify the group by replacing itself with EShowNext. So during the next call EShowNext will be executed. EShowNext in its turn replaces itself with ESkipNext and so on. As a result we will print every second item of the collection. A voila.

To be continued...

No comments:

Post a Comment