kdb/q: How to apply a string manipulation function to a vector of strings to output a vector of strings?

天大地大妈咪最大 提交于 2021-02-05 08:18:10

问题


Thanks in advance for the help. I am new to kdb/q, coming from a Python and C++ background. Just a simple syntax question: I have a string with fields and their corresponding values

pp_str: "field_1:abc field_2:xyz field_3:kdb"

I wrote an atomic (scalar) function to extract the value of a given field.

get_field_value: {[field; pp_str] pp_fields: " " vs pp_str; pid_field:  pp_fields[where like[pp_fields; field,":*"]]; start_i: (pid_field[0] ss ":")[0] + 1; end_i: count pid_field[0]; indices: start_i + til (end_i - start_i); pid_field[0][indices]}

show get_field_value["field_1"; pp_str]
"abc"

show get_field_value["field_3"; pp_str]
"kdb"

Now how do I generalize this so that if I input a vector of fields, I get a vector of values? I want to input ("field_1"; "field_2"; "field_3") and output ("abc"; "xyz"; "kdb"). I tried multiple approaches (below) but I just don't understand kdb/q's syntax well enough to vectorize my function:

/ Attempt 1 - Fail
get_field_value[enlist ("field_1"; "field_2"); pp_str]

/ Attempt 2 - Fail
get_field_value[; pp_str] /. enlist ("field_1"; "field_3")

/ Attempt 3 - Fail
fields: ("field_1"; "field_2")
get_field_value[fields; pp_str]

回答1:


To run your function for each you could project the pp_str variable and use each for the others

q)get_field_value[;pp_str]each("field_1";"field_3")
"abc"
"kdb"

Kdb actually has built-in functionality to handle this: https://code.kx.com/q/ref/file-text/#key-value-pairs

q){@[;x](!/)"S: "0:y}[`field_1;pp_str]
"abc"
q)
q){@[;x](!/)"S: "0:y}[`field_1`field_3;pp_str]
"abc"
"kdb"



回答2:


I think this might be the syntax you're looking for.

q)get_field_value[; pp_str]each("field_1";"field_2")
"abc"
"xyz"


来源:https://stackoverflow.com/questions/65441151/kdb-q-how-to-apply-a-string-manipulation-function-to-a-vector-of-strings-to-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!