Using pure to create immutable

Regan Heath regan at netmail.co.nz
Fri Sep 23 09:22:53 PDT 2011


On Thu, 22 Sep 2011 22:18:29 +0100, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:
> On Thursday, September 22, 2011 14:10 Steven Schveighoffer wrote:
>> No, the parameter types can be const, and can accept mutable arguments.
>> The main point is, the return value has to be proven to be *unique*. The
>> only way to do this with pure functions is to prove that the result is
>> *not* a subset of the parameters. That's all.
>>
>> Observe:
>>
>> char[] foo(const(char)[] x) pure {...}
>>
>> There is no way to write the body of this function such that the return
>> value is a substring of x. So you are guaranteed that the result is *new
>> memory*, and since it cannot be stored globally anywhere (per pure  
>> rules),
>> it's guaranteed to be unique, and should be implicitly castable to
>> immutable.
>>
>> Even if you pass a char[] into foo.
>
> Hmmmm. You're right. Bleh. This is overly complicated. It works, but  
> sorting
> it out is a pain. And trying to explain to newbies why and when a  
> function can
> have its return value implicitly converted to immutable... Well, it's  
> going to
> be an issue - just like with strong purity, but in that case at least,  
> we can
> pretty much just let the compiler optimize where it's going to optimize  
> and
> not generally worry about what's strong or weakly pure unless you're  
> really
> trying to optimize code. In this case, however, programmers are going to  
> need
> to understand in order to use it properly.

The key word here is "unique".  It "makes sense" that "unique" data can be  
implicitly cast to immutable, because it only exists once, in one place,  
and no-one/thing else knows about it.. therefore it can be considered  
immutable.

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list