//
// 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 -- test resolvers ability to deal with many variables with the same name and to use the minimum number of casts
//    necessary to disambiguate overloaded variable names.
//
// Author           : Peter A. Buhr
// Created On       : Wed May 27 17:56:53 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu May 26 09:25:42 2016
// Update Count     : 201
//

#include <fstream>

trait sumable( otype T ) {
	const T 0;
	T ?+?( T, T );
	T ?+=?( T *, T );
	T ++?( T * );
	T ?++( T * );
}; // sumable

forall( otype 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;
} // sum

// Required to satisfy sumable as char does not have addition.
const char 0;
char ?+?( char t1, char t2 ) { return (int)t1 + t2; }	// cast forces integer addition, otherwise recursion
char ?+=?( char *t1, char t2 ) { *t1 = *t1 + t2; return *t1; }
char ++?( char *t ) { *t += 1; return *t; }
char ?++( char *t ) { char temp = *t; *t += 1; return temp; }

int main( void ) {
	const int low = 5, High = 15, size = High - low;

	char s = 0, a[size], v = low;
	for ( int i = 0; i < size; i += 1, v += 1 ) {
		s += v;
		a[i] = v;
	} // for
	sout | "sum from" | low | "to" | High | "is"
		 | (int)sum( size, a ) | ", check" | (int)s | endl;

	int s = 0, a[size], v = low;
	for ( int i = 0; i < size; i += 1, v += 1 ) {
		s += (int)v;
		a[i] = (int)v;
	} // for
	sout | "sum from" | low | "to" | High | "is"
		 | sum( size, (int *)a ) | ", check" | (int)s | endl;

	float s = 0.0, a[size], v = low / 10.0;
	for ( int i = 0; i < size; i += 1, v += 0.1f ) {
		s += (float)v;
		a[i] = (float)v;
	} // for
	sout | "sum from" | low / 10.0 | "to" | High / 10.0 | "is"
		 | sum( size, (float *)a ) | ", check" | (float)s | endl;

	double s = 0, a[size], v = low / 10.0;
	for ( int i = 0; i < size; i += 1, v += 0.1 ) {
		s += (double)v;
		a[i] = (double)v;
	} // for
	sout | "sum from" | low / 10.0 | "to" | High / 10.0 | "is"
		 | sum( size, (double *)a ) | ", check" | (double)s | endl;

	struct S { int i, j; } 0 = { 0, 0 }, 1 = { 1, 1 };
	S ?+?( S t1, S t2 ) { return (S){ t1.i + t2.i, t1.j + t2.j }; }
	S ?+=?( S *t1, S t2 ) { *t1 = *t1 + t2; return *t1; }
	S ++?( S *t ) { *t += 1; return *t; }
	S ?++( S *t ) { S temp = *t; *t += 1; return temp; }
	ofstream * ?|?( ofstream * os, S v ) { return os | v.i | v.j; }

	S s = 0, a[size], v = { low, low };
	for ( int i = 0; i < size; i += 1, v += (S)1 ) {
		s += (S)v;
		a[i] = (S)v;
	} // for
	sout | "sum from" | low | "to" | High | "is"
		 | sum( size, (S *)a ) | ", check" | (S)s | endl;
} // main

// Local Variables: //
// tab-width: 4 //
// compile-command: "cfa sum.c" //
// End: //
