4 ms·
It happens by default in the sense that all standard library data structures in most functional programming languages implement data sharing so that new version
by dwohnitmok 7y ago
It happens by default in the sense that all standard library data structures in most functional programming languages implement data sharing so that new versions share any common data with the old version instead of being created by scratch. This is known as being a persistent data structure. Likewise custom types you make (the equivalent of say classes in an OO language) usually are implemented as referring to their subcomponents by reference rather than value (since everything is immutable the two are impossible to distinguish at the language level) and so your custom data structures also get this for free.
The only common immutable data structure that does not have a persistent/data sharing implementation is an immutable array (as opposed to a linked list or a tree structure approximating an array), since arrays must be contiguous sequences of memory and therefore parts cannot be shared (unless you count array slicing, where the new array is always a subarray). However, unless you have strict performance requirements, you generally can get away with not using an array, since arrays generally only offer performance benefits if they are primitive arrays (rather than arrays of pointers to other objects).
And if you do need a mutable array, there are ways of ensuring that its mutability doesn't spread out and "infect" other components of your system.
Generally speaking, yes the main loop ultimately is a tail recursive function. This does not turn out to be much of a constraint. This is because main generally returns Unit (what is called void in e.g. C or Java), and so generally does not make sense to put anywhere except in a tail position since it does not return a useful value to be used elsewhere.