kdb: check whether a symbol starts with a particular prefix

Viewed 306

Given a symbol, how to check whether it has a particular prefix?

I had below code. It checks if a symbol begins with aaaaa but returns 1b for aaa which is wrong. I can add a length check but that seems verbose. Is there a cleaner way?

{"aaaaa"~-5#string x}[`$"aaa"]
3 Answers

Could you use like?

q)`aaa like "aaa*"
1b 
q)`aaa like "aaaaa*"
0b

It seems like the issue is with "take" since "aaa" is shorter than 5. It's extending "aaa" by 2/3 of itself in order to meet that length.

You could modify your function so you have the following:

q){"aaaaa"~(x) til 5}["aaa"]
0b
q){"aaaaa"~(x) til 5}["aaaaaaaa"]
1b

Expanding on Matthew's answer if you want to make a function out of it do the following:

q)f:{x like "aaaaa*"}
q)f[`aaa]
0b
q)f[`aaaaa]
1b
q)f[`aaaaabcde]
1b

And if you want to make it more dynamic you could add a second variable for the matching prefix.

q)f2[`aaa;"aaa"]
1b
q)f2:{x like y,"*"}
q)f2[`aaa;"aaaaa"]
0b
q)f2[`aaa;"aaa"]
1b

Let me know if you see any issues.

Related