select()
Select one or more items from a list.
Synopsis
select(list-expression, expression)
select(list-expression, index-list-expression)
select(list-expression, test)
Description
The select()
function 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 function returns the item from the list with the
selected index.
In the second form above, the second argument evaluates to a list of index values, and the function returns a list consisting of the items in the first argument list with the selected indexes.
In the third form above, the second argument specifies a true-false
expression the function 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.
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 us 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.
Examples
Select the value 2
from the list expression list(1,2,3)
:
select(list(1,2,3), 1)
This example returns 0
since there is no value at position 3:
select(list(1,2,3), 3)
Select the first member of the given household:
first_housemate = select(members(Household), 0)
Select the positive numbers from a list:
positives_list = select(x_list, _>0)
Notes
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_list
select(x_list, ask(_,age)>18)
andx_list[ask(_,age)>18]
: returns the list of agents inx_list
that haveage > 18
.
Errors
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.