[86bd7c1f] | 1 | //
|
---|
| 2 | // Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
|
---|
| 3 | //
|
---|
| 4 | // The contents of this file are covered under the licence agreement in the
|
---|
| 5 | // file "LICENCE" distributed with Cforall.
|
---|
| 6 | //
|
---|
| 7 | // sum.c --
|
---|
| 8 | //
|
---|
| 9 | // Author : Richard C. Bilson
|
---|
| 10 | // Created On : Wed May 27 17:56:53 2015
|
---|
| 11 | // Last Modified By : Peter A. Buhr
|
---|
[6e7e2b36] | 12 | // Last Modified On : Mon Jun 1 20:46:35 2015
|
---|
| 13 | // Update Count : 18
|
---|
[86bd7c1f] | 14 | //
|
---|
| 15 |
|
---|
[a0d9f94] | 16 | extern "C" {
|
---|
[86bd7c1f] | 17 | int printf( const char *, ... );
|
---|
[a0d9f94] | 18 | }
|
---|
| 19 |
|
---|
| 20 | context sumable( type T ) {
|
---|
[86bd7c1f] | 21 | const T 0;
|
---|
| 22 | T ?+?( T, T );
|
---|
| 23 | T ?++( T * );
|
---|
| 24 | T ?+=?( T *, T );
|
---|
[a0d9f94] | 25 | };
|
---|
| 26 |
|
---|
| 27 | forall( type T | sumable( T ) )
|
---|
| 28 | T sum( int n, T a[] ) {
|
---|
[86bd7c1f] | 29 | T total; // instantiate T, select 0
|
---|
| 30 | total = 0;
|
---|
| 31 | for ( int i = 0; i < n; i += 1 )
|
---|
| 32 | total = total + a[i]; // select +
|
---|
| 33 | return total;
|
---|
[a0d9f94] | 34 | }
|
---|
| 35 |
|
---|
[bdd516a] | 36 | // Required to satisfy sumable as char does not have addition.
|
---|
| 37 | const char 0;
|
---|
| 38 | char ?+?( char op1, char op2 ) { return op1 + op2; }
|
---|
| 39 | char ?++( char *op ) { return *op + 1; }
|
---|
| 40 |
|
---|
| 41 | const double 0; // TEMPORARY, incorrect use of int 0
|
---|
| 42 |
|
---|
[a0d9f94] | 43 | int main() {
|
---|
[6e7e2b36] | 44 | const int low = 5, High = 15, size = High - low;
|
---|
| 45 | int si = 0, ai[size];
|
---|
| 46 | int v = low;
|
---|
| 47 | for ( int i = 0; i < size; i += 1, v += 1 ) {
|
---|
| 48 | si += v;
|
---|
| 49 | ai[i] = v;
|
---|
[86bd7c1f] | 50 | }
|
---|
| 51 | printf( "sum from %d to %d is %d, check %d\n",
|
---|
| 52 | low, High, sum( size, ai ), si );
|
---|
| 53 |
|
---|
[6e7e2b36] | 54 | // char ci[size];
|
---|
[86bd7c1f] | 55 | // char c = sum( size, ci );
|
---|
[6e7e2b36] | 56 | // float fi[size];
|
---|
[86bd7c1f] | 57 | // float f = sum( size, fi );
|
---|
| 58 |
|
---|
[6e7e2b36] | 59 | double sd = 0.0, ad[size];
|
---|
| 60 | double v = low / 10.0;
|
---|
| 61 | for ( int i = 0; i < size; i += 1, v += 0.1 ) {
|
---|
| 62 | sd += v;
|
---|
| 63 | ad[i] = v;
|
---|
[86bd7c1f] | 64 | }
|
---|
| 65 | printf( "sum from %g to %g is %g, check %g\n",
|
---|
[6e7e2b36] | 66 | low / 10.0, High / 10.0, sum( size, ad ), sd );
|
---|
[a0d9f94] | 67 | }
|
---|
[42dcae7] | 68 |
|
---|
| 69 | // Local Variables: //
|
---|
[86bd7c1f] | 70 | // tab-width: 4 //
|
---|
| 71 | // compile-command: "cfa sum.c" //
|
---|
[42dcae7] | 72 | // End: //
|
---|