Is it possible to write k code within q script?

Viewed 456

I tried calling count function of k from q function but it is giving error.

{
  "k)"# 1 2 3 4 5 //~ count 1 2 3 4 5
 }[]

So, I have below questions:
1. Is it possible to write k code within q script?
2. If yes, then how can we write k code in q script? and does using k code within q script/function make the script/function more efficient and optimised?

4 Answers
  1. Yes it is possible. I think what you are looking for is
{
 (#:) 1 2 3 4 5
}[]

This will perform a count on the list

  1. In terms of speed, for functions like count the effect seems to be negligible.
q)\t:100000 {(#:) 1 2 3 4 5}[]
29
q)\t:100000 {count 1 2 3 4 5}[]
25

Hope this answers your question

In addition to Eoins and pamphlets approaches, it's also possible to execute strings as k code:

q){a:"k" "|1 2 3";a}[]
3 2 1
q)
q){b:("k" "#:")1 2 3;b}[]
3

However there is practically no advantage to writing code as k code - better to stick with q

A k function can be defined within a lambda by the method that Terry laid out, or in general, by invoking the definition via value like so

q)mins
&\
q)foo:{[x] value "k)minner:&\\";minner x}
q)foo 1 2 3
1 1 1

In fact you can easily create a neat little function to create k functions

q)makeK:{[x;y]value "k)",string[x],"::",string[y]}
q)makeK[`minfoo;&\]
q)minfoo
&\
q)minfoo 1 2 3
1 1 1

Eoins answer is a neater way to invoke the k functionality of primitives. In general, wrapping primitives with parenthesis will invoke the k functionality

q)dict:`a`b`c!(1 2 3;1 2 3;1 2 3)
q)flip dict
a b c
-----
1 1 1
2 2 2
3 3 3
q)(+:) dict
a b c
-----
1 1 1
2 2 2
3 3 3
q)(+:)~flip
1b

You can. One approach is to define the entire function in k:

q)k)f:{# 1 2 3}
q)f
k){# 1 2 3}
q)f[]
3
Related