# Data structure thoughts for implementing lisp in C

This topic is 3493 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hey all! I've been thinking about writing my own little programming language (an interpreter first then possibly a compiler). To keep things simple I am using the prefix syntax of the lisp-style languages so I don't have to worry too much about complex parsing techniques. The issue I'm having is deciding a quick/efficient way of handling the core data type. I'd like things to be dynamic. Here's what I'm thinking about doing:
struct obj {
/* what type of value this object carries */
int type;

union {
char *id; /* identifier value */
int    i; /* integer value */
float  f; /* floating-point value */
char  *s; /* string value */

/* cons cell value */
struct {
struct obj *car;
struct obj *cdr;
} c;
} value;
};


The goal for the language to eventually be able to write something like:
(def square-value (n) (mult n n))
or..
(def greet (name) (print "Why, hello " name))

Which is why each object has to have the ability to be any possible type. Is there a better/faster/more efficient way to go about this in C? Any suggestions or comments would be appreciated! Thanks!

##### Share on other sites
Looks OK, but remember you'll need garbage collection done somehow.

##### Share on other sites
As mentioned before, GC would be a good idea. During your mark-and-sweep algorithm, you will basically copy your cons nodes to another area in memory, and will therefore need to point to the new position of every object that has already been moved by the garbage collector. So, I would suggest adding a new type:

struct obj {        /* what type of value this object carries */	int type;		union {                char        *id; /* identifier value */		int           i; /* integer value */		float         f; /* floating-point value */		char         *s; /* string value */                struct obj *mov; /* moved by GC */				/* cons cell value */		struct {			struct obj *car;			struct obj *cdr;		} c;	} value;};