« Can q script be compiled down to native code? | Main | How can I glue two tables side by side? »

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;

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Textile formatting is allowed.