Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing dynamic typing in C [duplicate]

Possible Duplicate:
Representing dynamic typing in C

A professor at my History of Computation side-lecture went into great depth about manifestly typed or type-inferred languages and generally praised the greatness of latently typed languages (faster dev times, dynamic systems, etc...).

The same day, at an Automata Class, another prof says:

Dynamic typing makes things more complex by adding more ways to do the same thing.

I've been using statically typed languages most of my life : C/C++/Java - my only exposure to the other has been Shell Coding and Ren'Py.

My question is, can I write a simple program in C that implements some of the benefits of both ?

For instance, I could create Unions to accept all user driven data, like so :

    typedef union {
        int int_type;
        char char_type;
        //and so on
    } dynamic;

   // Var Creation :
   dynamic data;

   // For unknown return type
   void* function(dynamic data);

I realize a Union could compromise type-safety, but that is what I'm trying to do here. What other approach could I take ? I'm just trying for a demonstration.

I tried for an answer from this question. But honestly, I could not follow the arguments closely.

I apologize if the question seems silly.

PS

Using suggestions from below, I wrote this : http://codepad.org/A9JAX8lD, which basically does nothing much dynamic, but is at least a start.
I think I see what both my professors were trying to say.

like image 515
RaunakS Avatar asked Apr 03 '12 09:04

RaunakS


2 Answers

My suggestion is not to try doing dynamic typing in a statically typed language. It will most likely have sub-par performance and a very strong syntactical burden. Instead, if you only ever have experienced statically typed languages, I would strongly suggest trying out Python. It is highly dynamic and will teach you new ways of thinking.

And last but not least, there also is Cython which is a Python dialect using C as intermediate language. It can mix static typing and dynamic typing, it's really refreshing.

like image 187
orlp Avatar answered Oct 03 '22 18:10

orlp


I'm not against types, but I don't know of any type systems that aren't a complete pain [...]
-- Alan Kay

It's quite possible to implement a fully-featured dynamic type system on top of C: Take GType, on which the GLib Object System is based.

However, such systems are often painful to use because of the amount of boilerplate code they need, which can be worked around by using custom code generators and preprocessors, which is how Objective-C got started.

like image 33
Christoph Avatar answered Oct 03 '22 18:10

Christoph