1Function: select
2Section: programming/specific
3C-Name: select0
4Prototype: GGD0,L,
5Help: select(f, A, {flag = 0}): selects elements of A according to the selection
6 function f. If flag is 1, return the indices of those elements (indirect
7 selection).
8Wrapper: (bG)
9Description:
10  (gen,gen):gen    genselect(${1 cookie}, ${1 wrapper}, $2)
11  (gen,gen,0):gen  genselect(${1 cookie}, ${1 wrapper}, $2)
12  (gen,gen,1):vecsmall  genindexselect(${1 cookie}, ${1 wrapper}, $2)
13Doc: We first describe the default behavior, when $\fl$ is 0 or omitted.
14 Given a vector or list \kbd{A} and a \typ{CLOSURE} \kbd{f}, \kbd{select}
15 returns the elements $x$ of \kbd{A} such that $f(x)$ is nonzero. In other
16 words, \kbd{f} is seen as a selection function returning a boolean value.
17 \bprog
18 ? select(x->isprime(x), vector(50,i,i^2+1))
19 %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]
20 ? select(x->(x<100), %)
21 %2 = [2, 5, 17, 37]
22 @eprog\noindent returns the primes of the form $i^2+1$ for some $i\leq 50$,
23 then the elements less than 100 in the preceding result. The \kbd{select}
24 function also applies to a matrix \kbd{A}, seen as a vector of columns, i.e. it
25 selects columns instead of entries, and returns the matrix whose columns are
26 the selected ones.
27
28 \misctitle{Remark} For $v$ a \typ{VEC}, \typ{COL}, \typ{VECSMALL},
29 \typ{LIST} or \typ{MAT}, the alternative set-notations
30 \bprog
31 [g(x) | x <- v, f(x)]
32 [x | x <- v, f(x)]
33 [g(x) | x <- v]
34 @eprog\noindent
35 are available as shortcuts for
36 \bprog
37 apply(g, select(f, Vec(v)))
38 select(f, Vec(v))
39 apply(g, Vec(v))
40 @eprog\noindent respectively:
41 \bprog
42 ? [ x | x <- vector(50,i,i^2+1), isprime(x) ]
43 %1 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]
44 @eprog
45
46 \noindent If $\fl = 1$, this function returns instead the \emph{indices} of
47 the selected elements, and not the elements themselves (indirect selection):
48 \bprog
49 ? V = vector(50,i,i^2+1);
50 ? select(x->isprime(x), V, 1)
51 %2 = Vecsmall([1, 2, 4, 6, 10, 14, 16, 20, 24, 26, 36, 40])
52 ? vecextract(V, %)
53 %3 = [2, 5, 17, 37, 101, 197, 257, 401, 577, 677, 1297, 1601]
54 @eprog\noindent
55 The following function lists the elements in $(\Z/N\Z)^*$:
56 \bprog
57 ? invertibles(N) = select(x->gcd(x,N) == 1, [1..N])
58 @eprog
59
60 \noindent Finally
61 \bprog
62 ? select(x->x, M)
63 @eprog\noindent selects the nonzero entries in \kbd{M}. If the latter is a
64 \typ{MAT}, we extract the matrix of nonzero columns. Note that \emph{removing}
65 entries instead of selecting them just involves replacing the selection
66 function \kbd{f} with its negation:
67 \bprog
68 ? select(x->!isprime(x), vector(50,i,i^2+1))
69 @eprog
70
71 \synt{genselect}{void *E, long (*fun)(void*,GEN), GEN a}. Also available
72 is \fun{GEN}{genindexselect}{void *E, long (*fun)(void*, GEN), GEN a},
73 corresponding to $\fl = 1$.
74