| Prev | Next | Start of Chapter | End of Chapter | Contents | Glossary | Index | Comments | (5 out of 14)

Populating A List

Use the insert action to populate an empty list. The insert action causes G2 to insert a list element. The syntax is:

When you specify an insert action, by using the before or after phrase:

Several ways to insert list elements are:


Notice that when you specify an insert item-or-value after the second type action, the list is noted twice: once to specify the list element and again to specify the list.


Note: If the Allow-duplicate-elements? attribute of any list is set to no and you attempt to insert a duplicate element, G2 signals an error.

Inserting Based on Element Location

To insert a list element based on element location:

For example:

Inserting at the Beginning or End of a List

To insert an element at the beginning or end of a list:

This action inserts item-or-value at the beginning or end of the specified g2-list. You must use the insert action to add elements to an empty list.

For example:


Inserting Before or After an Existing Element

To insert an element before or after an existing list element:

This action inserts item-or-value either before or after the existing element stated by item-or-value of a list.

For example:



Note: When you use the location before or after, the element before or after the element you are inserting must already exist; otherwise, G2 signals an error.

Inserting Into Lists With Duplicate Elements

When a list allows duplicate elements, using the insert and remove actions may produce unexpected results if you use either the second or next to last phrase, both of which evaluate to a value rather than a location.

Consider the example in the next diagram, in which an item list with duplicate elements contains several part numbers, and this expression indicates an insertion after the second element in the list:


The pointer in this diagram shows the desired position in the list:


When G2 evaluates this expression, it first obtains the value of the second item in the list, part-no-102 (this could also be an element index such as parts-shipped-list [ 1 ], for this example). G2 then searches the list from the first element to the last, and inserts the new element after the first occurrence of the given value. In this example, G2 inserts part-no-105 after the first element in the list (the first part-no-102) since it is the first occurrence of the second element value.

G2 guarantees to insert list elements after the first occurrence of an element value. Setting the Allow-duplicate-elements? attribute to no prevents positional ambiguity when inserting new list elements.

| Prev | Next | Start of Chapter | End of Chapter | Contents | Glossary | Index | Comments | (5 out of 14)

Copyright © 1997 Gensym Corporation, Inc.