Search code examples
kdbq-lang

kdb+/q: Check if argument has been supplied to the function call


Say we have function fun with two arguments, second one is optional. How to check within the function whether the second, optional argument has been supplied and act accordingly?

fun: {[x;optarg] $["optarg was supplied" like "optarg was supplied";"behavior 1"; "behavior 2"] }
fun[1;2] / behavior 1
fun[1]   / behavior 2

```


Solution

  • I don't think this is possible. Supplying less than the specified number of arguments result in a projection.

    A good alternative is to have your function accept one argument - a list. And then you can check for the existence of each element of the list.

    f:{[l] $[1=count[l]; 
                 / do something with first arg only; 
                 / do something with both args ] 
    }
    

    Or you could have the function accept a dictionary (this allows you to set default values in the function).

    q)f:{[dict] def:`a`b`c!10 20 30; 
                def:def upsert dict; 
                :def[`a] + def[`b] + def[`c] }
    
    
    q)f[`a`b!5 10]
    45
    
    q)f[`a`c!5 10]
    35