source: doc/theses/aaron_moss_PhD/phd/code/cfa-generic.cfa @ 48b7085e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 48b7085e 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: 661 bytes
RevLine 
[48b7085e]1#include <stdlib.h>
2#include <stdio.h>
3
4forall(otype T) struct list { T value; list(T)* next; };
5
6// single polymorphic implementation of each function
7// overloading reduces need for namespace prefixes
8
9forall(otype T) void insert( list(T)** ls, T x ) {
10        list(T)* node = alloc();  // type-inferring alloc
11        (*node){ x, *ls };  // concise constructor syntax
12        *ls = node;
13}
14
15forall(otype T) T head( const list(T)* ls ) { return ls->value; }
16
17// use is clear and efficient
18
19int main() {
20        list(int)* il = 0;
21        insert( &il, 42 );  // inferred polymorphic T
22        printf("%d\n", head(il));
23       
24        list(const char*)* sl = 0;
25        insert( &sl, "hello" );
26        printf("%s\n", head(sl));
27}
Note: See TracBrowser for help on using the repository browser.