Created
July 8, 2018 07:23
-
-
Save kawakami-o3/cfaa4313f2f00838c07558aeb733ba8b to your computer and use it in GitHub Desktop.
car, cons, add
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<stdlib.h> | |
| #define new(a) malloc(sizeof(a)) | |
| typedef struct { | |
| int i; | |
| } Atom; | |
| Atom *make_atom(int i) { | |
| //Atom *a = make( | |
| Atom *a = new(Atom); | |
| a->i = i; | |
| return a; | |
| } | |
| char *atom_to_string(Atom *a, char *s) { | |
| sprintf(s, "%d", a->i); | |
| } | |
| typedef struct List { | |
| Atom *atom; // to wrap | |
| struct List *car; | |
| struct List *cdr; | |
| } List; | |
| List *make_list() { | |
| List *l = new(List); | |
| l->atom = NULL; | |
| l->car = NULL; | |
| l->cdr = NULL; | |
| return l; | |
| } | |
| List *make_int(int i) { | |
| List *l = make_list(); | |
| l->atom = make_atom(i); | |
| return l; | |
| } | |
| int is_atom(List *lst) { | |
| return lst->atom != NULL; | |
| } | |
| List *car(List *lst) { | |
| if (lst->car == NULL) { | |
| printf("error"); | |
| exit(-1); | |
| } | |
| return lst->car; | |
| } | |
| List *cons(List *a, List *b) { | |
| List *l = make_list(); | |
| l->car = a; | |
| l->cdr = b; | |
| return l; | |
| } | |
| List *add(List *lst) { | |
| int i = 0; | |
| List *a = lst->car; | |
| List *d = lst->cdr; | |
| while (a != NULL) { | |
| printf("> %d\n", a->atom->i); | |
| i += a->atom->i; | |
| a = d->car; | |
| d = d->cdr; | |
| } | |
| return make_int(i); | |
| } | |
| int main() { | |
| List *nil = make_list(); | |
| List *a = make_int(10); | |
| List *b = make_int(20); | |
| List *c = make_int(30); | |
| List *args = cons(a, cons(b, cons(c, nil))); | |
| List *ret = add(args); | |
| char str[100]; | |
| atom_to_string(ret->atom, str); | |
| printf("%s\n", str); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment