4 ms·
Pure functional languages are capable of this, although they likely aren't modeling it as you envision. Pure record constructors let you do perform arbitrary m
by MasonOfSpoons 6y ago
Pure functional languages are capable of this, although they likely aren't modeling it as you envision. Pure record constructors let you do perform arbitrary mutation on the stack (e.g. calling other functions to build field values), but once the constructor is called the returned reference is immutable.
This is likely cleaner than sharing a reference which is sometimes mutable and sometimes not. Rust of course allows for both mutable and immutable borrows, and that's a very powerful tool but it'd be complex if all you needed was field initialization.
The consensus across languages that's emerged is that initialization shouldn't be a group effort, with references escaping in various stages of partial initialization. Be it RAII in C++ or functional record constructors, the common theme is that initialization should be a single operation that can succeed or fail as a whole.
- nostrademons 6y agoIt's the consensus among languages, but I've got a pretty large collection of application code that does need to partially initialize in passes, and there's also a fairly long list of escape hatches in languages (eg. lateinit in Kotlin, friend in C++, builder pattern in Java) to let you do this. Languages are supposed to capture common patterns; I'd argue this is a common pattern that isn't captured all that conveniently by existing language mechanisms, though a number have tried.