source: doc/theses/aaron_moss_PhD/phd/code/bespoke-generic.c @ 5c216b4

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 5c216b4 was 48b7085e, checked in by Aaron Moss <a3moss@…>, 6 years ago

Start into generic types design in thesis

  • Property mode set to 100644
File size: 986 bytes
Line 
1#include <stdlib.h>
2#include <stdio.h>
3
4struct int_list { int value; struct int_list* next; };
5
6void int_list_insert( struct int_list** ls, int x ) {
7        struct int_list* node = malloc(sizeof(struct int_list));
8        node->value = x; node->next = *ls;
9        *ls = node;
10}
11
12int int_list_head( const struct int_list* ls ) { return ls->value; }
13
14// all code must be duplicated for every generic instantiation
15
16struct string_list { const char* value; struct string_list* next; };
17
18void string_list_insert( struct string_list** ls, const char* x ) {
19        struct string_list* node = malloc(sizeof(struct string_list));
20        node->value = x; node->next = *ls;
21        *ls = node;
22}
23
24const char* string_list_head( const struct string_list* ls )
25        { return ls->value; }
26
27// use is efficient and idiomatic
28
29int main() {
30        struct int_list* il = NULL;
31        int_list_insert( &il, 42 );
32        printf("%d\n", int_list_head(il));
33       
34        struct string_list* sl = NULL;
35        string_list_insert( &sl, "hello" );
36        printf("%s\n", string_list_head(sl));
37}
Note: See TracBrowser for help on using the repository browser.