3

As a simplifying example, I have

tbl:flip `sym`v1`v2!(`a`b`c`d; 50 280 1200 1800; 40 190 1300 1900)

and I d like to pass a column name into a function like

f:{[t;c];:update v3:2 * c from t;} 

In this form it doesnt work. any suggestion how I can make this happen? Thanks

2
  • 2
    For your function definition you have some unnecessary semi-colons and you don't need to explicitly set the return with ":". Adding a semi-colon to the end of your update statement suppresses the output which is why you would need to set the return of the function but by removing that semi-colon the function will return the output automatically. So your function can look like f:{[t;c] update v3:2 * c from t} You can also see another example of this in Thomas' answer. Commented Feb 13, 2018 at 10:19
  • ah, thanks, good to know Commented Feb 13, 2018 at 10:20

2 Answers 2

5

Another option is to use the functional form of the update statement. https://code.kx.com/q/ref/funsql/#functional-sql

q)tbl:flip `sym`v1`v2!(`a`b`c`d; 50 280 1200 1800; 40 190 1300 1900)
q)parse"update v3:2*x from t"
!
`t
()
0b
(,`v3)!,(*;2;`x)
q){![x;();0b;enlist[`v3]!enlist(*;2;y)]} [tbl;`v2]
sym v1   v2   v3
------------------
a   50   40   80
b   280  190  380
c   1200 1300 2600
d   1800 1900 3800
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, looks like those functional forms are generally more flexible (and more confusing;))
3

One option to achieve this is using @ amend:

q){[t;c;n] @[t;n;:;2*t c]}[tbl;`v1;`v3]
sym v1   v2   v3
------------------
a   50   40   100
b   280  190  560
c   1200 1300 2400
d   1800 1900 3600

This updates the column c in table t saving the new value as column n. You could also alter this to allow you to pass in custom functions too:

{[t;c;n;f] @[t;n;:;f t c]}[tbl;`v1;`v3;{2*x}]

3 Comments

Thanks Thomas, that fixed my problem
curious, how come you pass in : as third argument and the function as part of the 4th? The documentation shows the function would be the 3rd argument. Is the colon here some sort of identity function?
In this case : is the function as we are setting a value, the 4th argument f t c will be resolved to a list of values. On the documentation this would be an example of the usage @[x;i;f;v] where v is the list of vectors created by f t c.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.