Entries in prototype (1)

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;