// // Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // sum.c -- // // Author : Peter A. Buhr // Created On : Wed May 27 17:56:53 2015 // Last Modified By : Peter A. Buhr // Last Modified On : Mon Jan 4 07:40:24 2016 // Update Count : 126 // #include "fstream.h" context sumable( type T ) { const T 0; T ?+?( T, T ); T ?+=?( T *, T ); T ++?( T * ); T ?++( T * ); }; forall( type T | sumable( T ) ) T sum( unsigned int n, T a[] ) { T total = 0; // instantiate T, select 0 for ( unsigned int i = 0; i < n; i += 1 ) 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 (int)op1 + op2; } // cast forces integer addition or recursion char ++?( char *op ) { *op += 1; return *op; } char ?++( char *op ) { char temp = *op; *op += 1; return temp; } int main( void ) { const int low = 5, High = 15, size = High - low; ofstream *sout = ofstream_stdout(); char s = 0, a[size]; char v = low; for ( int i = 0; i < size; i += 1, v += 1 ) { s += v; a[i] = v; } sout | "sum from " | low | " to " | High | " is " | (int)sum( size, a ) | ", check " | (int)s | endl; int s = 0, a[size]; int v = low; for ( int i = 0; i < size; i += 1, v += 1 ) { s += (int)v; a[i] = (int)v; } sout | "sum from " | low | " to " | High | " is " | sum( size, (int *)a ) | ", check " | (int)s | endl; double s = 0.0, a[size]; double v = low / 10.0; for ( int i = 0; i < size; i += 1, v += 0.1 ) { s += (double)v; a[i] = (double)v; } sout | "sum from " | low / 10.0 | " to " | High / 10.0 | " is " | sum( size, (double *)a ) | ", check " | (double)s | endl; float s = 0.0, a[size]; float v = low / 10.0; for ( int i = 0; i < size; i += 1, v += 0.1f ) { s += (float)v; a[i] = (float)v; } sout | "sum from " | low / 10.0 | " to " | High / 10.0 | " is " | sum( size, (float *)a ) | ", check " | (float)s | endl; } // Local Variables: // // tab-width: 4 // // compile-command: "cfa sum.c fstream.o iostream.o iterator.o" // // End: //