Entries in polymorphism (2)

Is function overloading supported in q?

Despite the fact that many native functions are overloaded, no. The last function definition simply overwrites the prior ones.

q)f: {[x]}
q)f: {[x; y]}
q)f
{[x; y]}
q)

Is polymorphism supported in q?

While q has no notion of inheritance, class, metaclass, or prototype, you can create structures packaged with associated functions and invoke those functions via the structures. Consider the following tired OO example expressed in q:

Draw: {[shape] shape[`draw] shape}

(Sadly, we cannot write shape.draw shape; dot notation is not supported for local variables, including arguments.)

Given an appropriate set of constructors -

NewCircle: {[x; y; radius]
`x`y`radius`draw ! (x; y; radius; {[circle] … })}
NewRectangle: {[x; y; w; h]
`x`y`w`h`draw ! (x; y; w; h; {[rect] …})}

etc, the following does exactly what you would expect:

shapes: (NewCircle[0; 0; 1];
         NewRectangle[-1; -2; 4; 2]);
Draw each shapes;