Function overloading with variable number of arguments

How can I make a function respond to the number of arguments? Thx.

f[1]

f[1;2]

f[1;2;3]

Pass a single parameter as a dictionary…

Sent from my iPhone

Use enlist.

q)f:{show x*x;}

q)func:('[f;enlist])

q)func[1]

,1

q)func[1;2]

1 4

q)func[1;2;3]

1 4 9

q)func[1;2;3;4;5;6;7;8;9;10]

1 4 9 16 25 36 49 64 81 100

f1[1]

f2[1;2]

f3orAbove[1;2;3]

fUnifiedInterface[var args]

The 3 functions may perform different calculations, not always the same thing like x^2.

You could try something like this

/-Assumption is that you have a function for each of the required number of values

/-List of functions depending on argument count

f1:{x+x}
f2:{x+y}
f3:{x+y+z}
f4:{[x;x1;y;z]prds (x;x1;y;z)}

/-create a step function where the count of argument selects out the required func

fd:`s#(1+til 4)!(f1;f2;f3;f4)

/-create projection to do lookup and apply argument

fc:{if[count[y]<t:count raze x;‘“No Func for No of args =”,string[t]];$[1=t;y[t]@x;y[t]. x]}[;fd]
f:(’[fc;enlist])

q)f[1]
,2
q)f[1;2]
3
q)f[1;2;3]
6
q)f[1;2;3;4]
1 2 6 24
q)f[1;2;3;4;5]
'No Func for No of args =5

Thanks Rory

Hi,
i think you should NOT do this. 

in k/q every function has a defined number of arguments which is not variable.

if you run a function with less parameters it is “projected” (other languages also call this function currying): http://code.kx.com/wiki/JB:QforMortals/functions#Projection

so you get a new function with some parameters already set. This is a very nice feature but conflicts with function overloading.

The above example use the verb each to modify the behaviour of a function. As demonstrated this does work to solve your question. But I consider it an ugly style. And as 

you can see the code is not easily readable.

My advise: Do not use this. Create different functions. And use them as needed.

Markus

> i think you should NOT do this. 
great answer thx :)