Last change
on this file since b28ce93 was 48b7085e, checked in by Aaron Moss <a3moss@…>, 7 years ago |
Start into generic types design in thesis
|
-
Property mode
set to
100644
|
File size:
661 bytes
|
Line | |
---|
1 | #include <stdlib.h>
|
---|
2 | #include <stdio.h>
|
---|
3 |
|
---|
4 | forall(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 |
|
---|
9 | forall(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 |
|
---|
15 | forall(otype T) T head( const list(T)* ls ) { return ls->value; }
|
---|
16 |
|
---|
17 | // use is clear and efficient
|
---|
18 |
|
---|
19 | int 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.