A tiny template for averaging numbers.
I needed this for a prototype and I didn’t want to “wing it” anymore.
I think there should be a package with similar templates that people could download to enhance the language, I’m just saying… It takes little to come up with this kind of code and in the end it’s always useful to have it around.
Macro Average_Register( _type ) Structure AVERAGE#_type sum._type average._type count.i EndStructure Procedure.i Average#_type#_Create() Define.AVERAGE#_type *this = AllocateMemory( SizeOf( AVERAGE#_type ) ) ProcedureReturn *this EndProcedure Procedure.i Average#_type#_Destroy( *this.AVERAGE#_type ) FreeMemory( *this ) *this = #Null EndProcedure Procedure._type Average#_type#_Calculate( *this.AVERAGE#_type ) If *this\count And *this\sum *this\average = ( *this\sum / *this\count ) ProcedureReturn *this\average EndIf EndProcedure Procedure.i Average#_type#_Reset( *this.AVERAGE#_type ) *this\sum = 0.0 *this\average = 0.0 *this\count = 0 EndProcedure Procedure.i Average#_type#_Add( *this.AVERAGE#_type, sample.f ) *this\sum + sample *this\count + 1 EndProcedure Procedure.i Average#_type#_Count( *this.AVERAGE#_type ) ProcedureReturn *this\count EndProcedure Procedure._type Average#_type#_Sum( *this.AVERAGE#_type ) ProcedureReturn *this\sum EndProcedure Procedure._type Average#_type#_Get( *this.AVERAGE#_type ) ProcedureReturn *this\average EndProcedure EndMacro |
You may register it as any numerical type.
Usage example:
Average_Register( f ) ; register with floats. Define.AVERAGEf test Averagef_Add( test, 1.0 ) Averagef_Add( test, 2.0 ) Averagef_Add( test, 3.0 ) Averagef_Add( test, 4.0 ) Averagef_Add( test, 5.0 ) Debug Averagef_Calculate( test ) Debug Averagef_Count( test ) Debug Averagef_Sum( test ) Averagef_Reset( test ) Debug Averagef_Calculate( test ) Debug Averagef_Count( test ) Debug Averagef_Sum( test ) |
You can allocate an instance of the structure with the Create function.
For example, if you registered the template as float, then you may create a dynamic “object” in this way:
Define.AVERAGEf *test = Averagef_Create() ; the *test variable holds an instance of the AVERAGEf structure |
Likewise, you should call the Destroy() function to get rid of it.
Averagef_Destroy( *test ) |
Trivial but useful. I’m not particularly happy with the naming convention though. But, let’s not forget that this is not an attempt at emulating OOP at all; it’s just a way of giving flexibility to an encapsulated piece of code. For OOP there are proper languages and there is no point whatsoever in trying to emulate it.
Cheers