What purpose to const besides functional programming?

Walter Bright newshound1 at digitalmars.com
Tue Jul 22 17:35:16 PDT 2008


Jason House wrote:
> Walter Bright Wrote:
>> It is one of the points of the const system. But the idea is not to
>> just declare things invariant and magically they will work in
>> functional style. The idea is that if you want to make something
>> functional, the language will provide support for it if only in the
>> form of telling you when something will not work in functional
>> style. That appears to be the case with bar() - it cannot work in
>> functional style.
> 
> Can you answer this more thoroughly?  It's really important to this
> dialog.  What *other* purposes does the const system serve besides
> opening the door to functional programming?  I understand that the
> const system must remain simple to be usable.

1. It makes function APIs self-documenting.
2. Invariance allows one to pass large data structures around by 
reference yet treat them as if one passed them by value. Strings are the 
canonical example of that.
3. Const allows one function to service both mutable and invariant 
arguments.
4. Invariant data can be placed in hardware protected readonly memory, 
such as ROM.
5. Invariant data does not have to be synchronized to be multithread 
accessible.
6. Invariant data improves the ability of automated tools to make 
inferences about what is happening. Optimization is an example of such.

>> The missing ingredient here is what the 'pure' modifier for
>> functions provides. That is the ability to diagnose attempts to
>> alter global state from within a function that is not supposed to
>> do that. Invariant does not imply pure.
> 
> That's actually a very key part to my whole point.  There is very
> little difference between pure and invariant functions.  Why do we
> need a concept for both?  Under the assumption that we're adding
> const to support functional programming, I don't understand the
> motivation for this difference.

See points 1..5.

> Pure functions requires that any shared data is invariant.

Yes, but invariant data does not require purity.

> The net effect is that D currently contains two
> concepts - invariant functions and pure functions.

Yes.

> Based on principles 1&2, I can't justify the extra complexity.

I can with points 1..5.

> I believe that I understand, and hope my more verbose post above will
> help convince you of that.  I believe (nievely?) that I have value to
> add if only I can convince you.  I truly do think what I've outlined
> is a problem with the D const system.

I hope this post will convince you otherwise. If not, I can try again <g>.



More information about the Digitalmars-d mailing list