How do I use the functional forms of apply and amend?
Typical q code operates on all of the elements of a container at once:
q)container: 1 2 3
q)100 * container
100 200 300
q)
Sometimes we are interested in only a subset of elements from a container:
q)container: til 10
q)container
0 1 2 3 4 5 6 7 8 9
q)container[where 0 = container mod 2]
0 2 4 6 8
q)
Sometimes, however, you need to update particular elements of a structure while leaving the remaining elements unchanged. That’s what functional apply and amend are for; they transform specific elements of a container without touching the others. The variations are distinguished by 3 choices:
Which operator is used, @ or ., determines the interpretation of the indices used to select the elements to transform.
- container or name
The first argument is either the value of a container or the name of a global variable referring to a container. In the former case, a new object is returned; in the latter, the global variable is modified and its name is returned.
- monadic or dyadic function
If the transformation requires additional information beyond that contained in each element itself, that is accomplished by using a dyadic function and supplying the additional information in a fourth argument to the operator.
For a detailed discussion, please see the following faqs:
Lastly, note that there is another pair of overloads for @ and . – each with three arguments – called protected execution, which are invoked when the first argument to @ or . is a function or projection; protected execution is discussed in another faq.