Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

ITT: cons in our favorite language

Name: Anonymous 2008-10-03 23:43


typedef struct
{
    void * car;
    void * cdr;
}pair;

pair * cons(void * car, void * cdr)
{
    pair * toCons = malloc(sizeof(pair));
    toCons->car = car;
    toCons->cdr = cdr;
    return toCons;
}

Name: Anonymous 2008-10-04 6:46

Simple crap:

cons = lambda x, y: (x, y)
car = lambda x: x[0]
cdr = lambda x: x[1]


Functional fapping:

cons = lambda x, y: lambda f: f(x, y)
car = lambda x: x(lambda x, y: x)
cdr = lambda x: x(lambda x, y: y)


OOP fapping:

class cons(object):
    def __init__(self, car, cdr):
        self.car, self.cdr = car, cdr
car = lambda c: c.car
cdr = lambda c: c.cdr


The last implementation is the best, because it introduces semantics (you can check whether something is a cons cell with type(x) is cons; in other words you can implement pair?, which can be done in the second version but you have to check the func_code.co_code), and because you can use it with either the car and cdr functions, or the car and cdr properties.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List