Franz Wong
Franz Wong

Reputation: 1124

Concat string with number in kdb+ q

I can append a string with number.

temp:30
text:"Current temperature is ",string temp
show text
type text

Result

"Current temperature is 30"
10h

However, if I append one more string, it becomes a list. (why?)

text:"Current temperature is ",string temp," degree celsius"
show text
type text

Result

C
u
r
r
e
n
t
 
t
e
m
p
e
r
a
t
u
r
e
 
i
s
..
0h

I can use sv with empty string as delimiter, is it the normal way to do it?

text:"" sv ("Current temperature is ";string temp;" degree celsius")

Upvotes: 0

Views: 507

Answers (3)

To add to Maurice Lim's answer, this is because of the way q evaluates expressions. Expressions are evaluated left-of-right (which means expressions are evaluated right-to-left).

https://code.kx.com/q4m3/4_Operators/#412-left-of-right-evaluation

The concatenation operator therefore works first on

temp," degree celsius"

which becomes a mixed list. And mixed lists are displayed exactly the way you got your first result.

Using square brackets, changes the order of evaluation (because it binds temp to the function string) and therefore evaluates string[temp] first. Then you concatenate two strings which returns a simple list.

Upvotes: 1

Maurice Lim
Maurice Lim

Reputation: 883

You should change it to

text:"Current temperature is ",string [temp]," degree celsius"

Your string function is working on: temp," degree celsius" but you just need to string[temp] to concat it.

Upvotes: 3

user1874594
user1874594

Reputation: 2493

comma operator treats each character in the concatenated string as a separate item and creates a list of those characters.

On the other hand, when you use sv with an empty string as the delimiter, it joins all the strings in the list into a single string, which is the desired behavior for concatenation.

Upvotes: 0

Related Questions