Monkey
Store
Community
Apps
Contact
Login or Signup

Suggestion: generic functions

Monkey Programming Forums/Monkey Programming/Suggestion: generic functions

Gerry Quinn(Posted 1+ years ago) 
Hi,

This post grew out of a discussion called 'Randomising an Array'. I was interested in making a generic shuffling function that would shuffle (say) an array of Card objects.

My first thought was that an object array is surely just an array of pointers in reality, so it should be possible to just downcast them to object pointers and shuffle any array of objects without generics at all. Unfortunately that doesn't seem to be possible (why?).

I found I could do it with a generic class

Class ArrayRandomiser< T >
	Method New( _arr:T[], nToSwap:Int = -1 )
		' code removed for brevity	
	End
End


Then to use it I just write:
New ArrayRandomiser< Card >( myCardArray )


However I thought it would be nice to have proper generic functions without the extraneous 'New'. I thought to make a class called Generic which would hold functions such as ArrayRandomiser. It looks like:

Class Generic< T >

	Method RandomiseArray:Void( _arr:T[], nToSwap:Int = -1 )
		' code removed
	End

	' more methods...	
End


This works too but the syntax for using it is pretty horrid - I have to write:
New Generic< Card >().RandomiseArray( myCardArray )


Anyway, it occurred to me that generic functions could be added to Monkey very easily by just replicating behind the scenes what I did here. Suppose you wrote code like:

Function< T > RandomiseArray:Void( _arr:T[] )


It would be converted into a method of a hidden class like my Generic< T >. Then when you call the function, like:

RandomiseArray( myCardArray )


..it would be converted into:

New Generic< Card >().RandomiseArray( myCardArray )


...and compiled as normal. This conversion should be simple because the type of myCardArray is known at compile time.

Actually it occurs to me that maybe it is not quite so simple if there are a lot of methods with the same name and different signatures. So there could be an option to specify it with:

RandomiseArray<Card>( myCardArray ) 


Anyway, just a suggestion. For now I'll carry on with the class method which works fine! It just seems like there should be a more elegant way than instantiating classes that don't really need to exist.