extern "C" { int printf( const char *, ... ); } context sumable( type T ) { const T 0; T ?+?( T, T ); T ?++( T * ); T ?+=?( T *, T ); }; forall( type T | sumable( T ) ) T sum( int n, T a[] ) { T total; // instantiate T, select 0 total = 0; for ( int i = 0; i < n; i += 1 ) total = total + a[i]; // select + return total; } // Required to satisfy sumable as char does not have addition. const char 0; char ?+?( char op1, char op2 ) { return op1 + op2; } char ?++( char *op ) { return *op + 1; } const double 0; // TEMPORARY, incorrect use of int 0 int main() { const int size = 10, low = 0, High = 10; int si = 0, ai[10]; // size int i; for ( i = low; i < High; i += 1 ) { si += i; ai[i] = i; } printf( "sum from %d to %d is %d, check %d\n", low, High, sum( size, ai ), si ); // char ci[10]; // char c = sum( size, ci ); // float fi[10]; // float f = sum( size, fi ); double sd = 0.0, ad[10]; // size for ( i = low; i < High; i += 1 ) { double d = i / (double)size; sd += d; ad[i] = d; } printf( "sum from %g to %g is %g, check %g\n", low / (double)size, High / (double)size, sum( size, ad ), sd ); } // Local Variables: // // compile-command: "../../bin/cfa sum.c" // // End: //