memberModify!
Syntax
memberModify!(obj, function, indices, [parameters])
Arguments
obj is a tuple, a dictionary with values of ANY type, or a class instance.
function is a built-in function that accepts a mutable first parameter (e.g.,
append!
).
indices specifies which members to modify. It can be:
- A scalar: Modifies a single member
- A vector: Modifies multiple members, with each element identifying a member
- A tuple: Modifies one or multiple members through multi-dimensional indexing, where tuple length represents indexing depth
parameters(optional) indicates additional parameters passed to function after its first parameter. If function only takes a single parameter (obj), leave parameters unspecified or pass an empty tuple.
Details
Modifies one or more member objects of obj by applying a specified function with given parameters.
Examples
Example 1. Modifying a member object in a tuple.
a = (1 2, 3 4 5)
memberModify!(a, append!, 0, 3 4)
a //output:(1 2 3 4, 3 4 5)
To pass a tuple as a single argument to function, the tuple must be enclosed
in additional brackets or converted using enlist
. Without this,
each element of the tuple becomes an independent argument.
a = ((1, `b), 3 4 5)
memberModify!(a, appendTuple!, 0, (2 `c))
// Error: appendTuple!(X, Y, [wholistic=false]). Y must be a tuple.
memberModify!(a, appendTuple!, 0, enlist((2 `c))) //output: ((1,"b",2,"c"),[3,4,5])
// equivalent to memberModify!(a, appendTuple!, 0, [(2 `c)])
When function accepts only obj with no additional parameters, parameters should be left unspecified or set as an empty tuple:
a = (1 2, 3 4 5)
memberModify!(a, pop!, 0) //output: ([1],[3,4,5])
//equivalent to memberModify!(a, pop!, 0, ())
Example 2. Modifying values in a dictionary.
d = dict(`A`B`C, (1 2, 3 4, 5 6))
d
/*output:
A->[1,2]
B->[3,4]
C->[5,6]
*/
d.memberModify!(append!,`A`B, 3 4)
d
/*output:
A->[1,2,3]
B->[3,4,4]
C->[5,6]
*/
Example 3. Using tuple indices
Create a tuple consisting of a table, a dictionary, and a tuple.
t = table(1 2 3 as val1, 4 5 6 as val2)
d = dict(`A`B`C, (1 2, 3 4, 5 6))
c = (t, d, [1 2 3, 4 5 6])
c
/*output:
(val1 val2
---- ----
1 4
2 5
3 6
,C->[5,6]
A->[1,2]
B->[3,4]
,([1,2,3],[4,5,6]))
*/
To modify a nested vector in the tuple object using memberModify!
,
use a tuple indices for multi-dimensional indexing:
c.memberModify!(append!, (2, 0), 4 5)
/*output:
(val1 val2
---- ----
1 4
2 5
3 6
,C->[5,6]
A->[1,2]
B->[3,4]
,([1,2,3,4,5],[4,5,6]))
*/
To modify a value in the dictionary object, also use a tuple indices:
c.memberModify!(append!, (1,`B), 5 7)
c
/*output:
(val1 val2
---- ----
1 4
2 5
3 6
,C->[5,6]
A->[1,2]
B->[3,4,5,7]
,([1,2,3,4,5],[4,5,6]))
*/
Example 4. Modifying members of a class instance:
class A {
a :: INT VECTOR
def A() {
a = []
}
}
v = A()
memberModify!(v, append!, "a", 1) # Adds 1 to vector a
//output: [1]
memberModify!(v, append!, "a", 11) # Adds 11 to vector a
//output: [1,11]