Do pure functions solve the "return const" problems?

Russell Lewis webmaster at villagersonline.com
Tue Apr 1 10:44:21 PDT 2008


I've been pondering the discussions about "return const" and such. 
Basically, the idea is to be able to define a function which is not 
allowed to modify certain data, but which can return subsets of that 
data in a non-const fashion.  Classic examples are strstr (scan, but 
don't alter, the data, but return a usable pointer) and min/max (compare 
the items and return one, but return non-const versions of them).

Are pure functions the way?  Isn't a pure function required to not 
modify the data?  And, for that reason, can't a pure function be utterly 
ignorant of the const-ness of the data?


BEGIN CODE
	pure char[] strstr(char[] haystack, char[] needle)
	{
		// perform the search
		int indx = <whatever>

		return haystack[indx..$];
	}
END CODE


Of course, somebody's going to post an example of a function which is 
inherently non-pure but which needs this sort of functionality.  I can't 
think of exactly what it would be, but let's assume that somebody does. 
  In this case, a "pure delegate" could handle it:


BEGIN CODE
	char[] pure delegate(char[])
	myBadlyBehavedFunction(string input, ....other args...)
	{
		int indx = <whatever>;

		return pure delegate char[](char[] input)
		       {
		         return input[indx..$];
		       };
	}
END CODE


So, the function which makes the decision isn't pure, but the delegate 
that it returns *is*, so a caller can happily and confidently do:


BEGIN CODE
	void foo()
	{
		char[] thing = <my critical data>;
		char[] subset = myBadlyBehavedFunction(thing) (thing);
	}
END CODE


If this was important enough of a pattern, we could even give syntax 
sugar for it.


Thoughts?
	Russ



More information about the Digitalmars-d mailing list