[a0d9f94] | 1 | extern "C" { |
---|
| 2 | int printf( const char *, ... ); |
---|
| 3 | } |
---|
| 4 | |
---|
| 5 | context sumable( type T ) { |
---|
| 6 | const T 0; |
---|
[42dcae7] | 7 | T ?+?( T, T ); |
---|
| 8 | T ?++( T * ); |
---|
[bdd516a] | 9 | T ?+=?( T *, T ); |
---|
[a0d9f94] | 10 | }; |
---|
| 11 | |
---|
| 12 | forall( type T | sumable( T ) ) |
---|
| 13 | T sum( int n, T a[] ) { |
---|
[bdd516a] | 14 | T total; // instantiate T, select 0 |
---|
| 15 | total = 0; |
---|
[42dcae7] | 16 | for ( int i = 0; i < n; i += 1 ) |
---|
| 17 | total = total + a[i]; // select + |
---|
[a0d9f94] | 18 | return total; |
---|
| 19 | } |
---|
| 20 | |
---|
[bdd516a] | 21 | // Required to satisfy sumable as char does not have addition. |
---|
| 22 | const char 0; |
---|
| 23 | char ?+?( char op1, char op2 ) { return op1 + op2; } |
---|
| 24 | char ?++( char *op ) { return *op + 1; } |
---|
| 25 | |
---|
| 26 | const double 0; // TEMPORARY, incorrect use of int 0 |
---|
| 27 | |
---|
[a0d9f94] | 28 | int main() { |
---|
[42dcae7] | 29 | const int size = 10, low = 0, High = 10; |
---|
[bdd516a] | 30 | int si = 0, ai[10]; // size |
---|
[42dcae7] | 31 | int i; |
---|
| 32 | for ( i = low; i < High; i += 1 ) { |
---|
| 33 | si += i; |
---|
| 34 | ai[i] = i; |
---|
[a0d9f94] | 35 | } |
---|
[42dcae7] | 36 | printf( "sum from %d to %d is %d, check %d\n", |
---|
| 37 | low, High, sum( size, ai ), si ); |
---|
[bdd516a] | 38 | |
---|
| 39 | // char ci[10]; |
---|
| 40 | // char c = sum( size, ci ); |
---|
| 41 | // float fi[10]; |
---|
| 42 | // float f = sum( size, fi ); |
---|
| 43 | |
---|
| 44 | double sd = 0.0, ad[10]; // size |
---|
[42dcae7] | 45 | for ( i = low; i < High; i += 1 ) { |
---|
| 46 | double d = i / (double)size; |
---|
| 47 | sd += d; |
---|
| 48 | ad[i] = d; |
---|
| 49 | } |
---|
| 50 | printf( "sum from %g to %g is %g, check %g\n", |
---|
| 51 | low / (double)size, High / (double)size, sum( size, ad ), sd ); |
---|
[a0d9f94] | 52 | } |
---|
[42dcae7] | 53 | |
---|
| 54 | // Local Variables: // |
---|
| 55 | // compile-command: "../../bin/cfa sum.c" // |
---|
| 56 | // End: // |
---|