3

How I may update values in q dictionary use functional way?

Example:

x: `1`2`3;
d: x!x;
show[d];
// d -> 
// 1 | 1
// 2 | 2
// 3 | 3
// TODO change d: 
show[d];
// d -> 
// 1 | 11
// 2 | 22
// 3 | 3
G. A.
  • 25
  • 4
Alykoff Gali
  • 1,121
  • 17
  • 32

4 Answers4

5

You may change you dictionary in this way:

// @[dictionary name; list of keys; ?; list of values];
@[d; `1`2; :; `11`22];
Alykoff Gali
  • 1,121
  • 17
  • 32
3

It is also possible to functionally update a dictionary with standard amend/set syntax (using ":") as follows:

q)x:1 2 3

q)d:x!x

q)d
1| 1
2| 2
3| 3

q)f:{d[x]:y}
q)f[2;7]

q)d
1| 1
2| 7
3| 3

This also works for vectors provided they are of the same length :

q)f[1 2;5 6]
q)d
1| 5
2| 6
3| 3
Paul Kerrigan
  • 465
  • 5
  • 12
1

Another way:

q)x:1 2 3;
q)d:x!x;
q)d
  1| 1
  2| 2
  3| 3
q)d,: enlist[2]!enlist[5];
q)d
  1| 1
  2| 5
  3| 3
q)d,: (2 3)!(7 7);
q)d
  1| 1
  2| 7
  3| 7
G. A.
  • 25
  • 4
0

You can use a simple amend on the key you wish to change.

q)d[1 2]+:10
q)d
1| 11
2| 12
3| 3

This is the equivalent of

d[1 2]:d[1 2]+10

or

d[1 2]:11 12

Here there is no real need for a functional apply to change the values in the dictionary.

Gilmer
  • 410
  • 3
  • 8