select¶
Syntax¶
select(list-expression, expression)
select(list-expression, index-list-expression)
select(list-expression, test)
Parameters¶
list-expression- An expression that evaluates to the list to select from.
expression- An expression that evaluates to a number. This is used as an index into the list.
index-list-expression- An expression that evaluates to a list representing the positions of the items to select (the first item has position
0). test- A true-false expression that is evaluated for each item in the list.
Returns¶
The first form returns the selected list item or 0.
The second and third forms return a list of items, which may be empty.
Description¶
Selects one or more items from a list. The select() action has three forms.
In all forms, the form argument is a list-expression that evaluates to a list.
In the first form above, the expression is evaluated to produce an index, and
the action returns the item from the list with the selected index.
Note
If the expression has decimal digits, they will be truncated.
In the second form above, the second argument evaluates to a list of index values, and the action returns a list consisting of the items in the first argument list with the selected indices.
In the third form above, the second argument specifies a true-false expression the action returns a list consisting of the all items in the first argument list for which the expression returns true. The special variable _ in the test refers to the list item being evaluated.
Examples¶
Select the value 2 from the list expression list(1,2,3):
This example returns 0 since there is no value at position 3:
Select the first member of the given household:
Select the positive numbers from a list:
In the first and second form, the index values are truncated to integers.
If X is declared as a list variable, then the parser translates
X[string] to select(X,string), so the following are equivalent:
select(x_list, index_list)andx_list[index_list]select(x_list, _>0)andx_list[_>0]: returns all positive numbers inx_listselect(x_list, ask(_,age)>18)andx_list[ask(_,age)>18]: returns the list of agents inx_listthat haveage > 18.
In the first and second form, it is a run-time error if an index evaluates to a negative value or a value greater than the size of the list.