pure or not pure?
Georg Wrede
georg at nospam.org
Thu Apr 10 10:54:47 PDT 2008
Steven Schveighoffer wrote:
> Now, I realize I have very similar code that initializes the int arrays, so
> I want to put that into a function that creates and initializes an array
> with the given parameters:
>
> int[] createIncreasingSequence(int length, int start, int step)
> {
> int[] result = new int[length];
> for(int i = 0; i < result.length; i++)
> result[i] = start + (i * step);
> return result;
> }
>
> Now, I think we all agree that createIncreasingSequence is as pure as
> calling new, right? That is, it doesn't affect any global state (except for
> allocating heap data) and will return an equivalent array every time the
> same arguments are given. But if I can't declare it as 'pure', then I can't
> call it from f and g:
Yes. I think your function is pure. Except for the fact that the
returned heap data has to be pure.
> pure int f()
> {
> int[] x = createIncreasingSequence(5, 1, 1);
>
> /* do stuff */
> return result;
> }
>
> pure int g()
> {
> int[] y = createIncreasingSequence(15, 10, 3);
>
> /* do stuff */
> return result;
> }
>
> So should there be a way to define createIncreasingSequence such that I can
> call it from a pure function? Or do I have to re-implement it in every pure
> function I use?
You should be able to call it from a pure function.
> Not having the ability to pass around mutable heap data to and from pure
> functions is going to limit severely the usefulness of pure functions.
This example does not need mutable data. And it is an example of how you
can get along just fine with immutable data.
(It is also an example of CTFE. That is, already existing DMD should
convert f and g into compile time constants. :-) But that's obviously
besides the point here!)
More information about the Digitalmars-d
mailing list