Polymorphic Functions

I have to confess that so far I have been side-stepping around the issue of polymorphic functions in Cat. I had been using dynamic typing and implementation magic to make functions like “add” work, where add means either “add_ints” or “add_doubles”. The problem is identifying precisely what it means in a statically typed language to push the “add” function onto the stack.

I am currently considering implementing polymorphic functions, such as add, as follows:

define add : (’a ’a -> ‘a) { typeof (int, double) ([add_int], [add_double]) switch eval }

This is admittedly not very convenient for the average user but since Cat is mostly intended as an intermediate language, I think we can live with this as a dynamic dispatch mechanism.

3 Responses to “Polymorphic Functions”

  1. sjprouty Says:

    Is “dup” considered a polymorphic function? If there is an int on the stack, it has to do something like dup_int, and if there is a double on the stack it has to do something like dup_double. This same reasoning could be extended to “pop” and “swap”.

    In PostScript, items on the stack are called “objects”. These “objects” have attributes, one of which is called “type”. Some operators like “dup” do not care about an object’s type, while other operators like “add” do care about an object’s type. So in a sense there is one base type (an “object”) which itself has sub-types (the object’s “type” attribute).

    Thanks
    Scott Prouty

  2. cdiggins Says:

    Yes “dup”, “pop”, “swap”, etc. are all polymorphic.

    To a large degree a user doesn’t care about the types for those operations, but for some operations such as “dup” an implementation does care whether to use copying or moving semantics. So in this case we are concerned with whether an object’s type has copying or sharing semantics. This comes into play when generating assembly code.

    However such concerns are mostly invisible to a user, and is more of an implementation issue. For example “dup” always appears as a copying operation, since sharing is only possible while an object is not modified.

    Hopefully this makes some sense?

  3. sjprouty Says:

    Yes, it makes sense.

    BTW, I did make a mistake in my earlier post. I said in PostScript “dup” does not care about an object’s type. Actually, it does to a degree. If the object is a simple type, “dup” does a copy. If the object is a composite type, “dup” creates a shared object.

    Thanks
    Scott Prouty

Leave a Reply

You must be logged in to post a comment.