The pattern you describe looks a lot like a constructor in object-oriented programming; while fields are not necessarily immutable, it is common practice to build your objects to be immutable except for the constructors, e.g., in a hypothetical OOP language:
class NumberSequenceString {
private string val;
public function __construct(top) {
val = "";
for (i = 1; i <= top; i++)
val = val + (string)i;
val = val + "z";
}
public getVal() { return val; }
}
var myString = new NumberSequenceString(10);
(I took the liberty to make your code sample a bit more interesting: instead of repeating "z" 10 times, it now spits out the string "12345678910z"
; the code required to build this string is just complex enough to demonstrate nontrivial processing later).
However, most functional programming idioms take a different route; instead of distinguishing between the "uninitialized", "constructing" and "immutable" phases of a variable's life cycle, they just eliminate the first two: a variable's life cycle starts when it is defined, and the definition already provides the only value it will every have. This is possible because the functional programming idiom favors powerful expressions over statements, which means that the value you're assigning can itself be constructed in just one expression; instead of using iterative loops with a mutable counter variable, functional programmers think in terms of map
and reduce
. Your example in functional style would look something like this:
function makeSequenceString(top) {
return range(1, top).map(toString).reduce(+) + "z";
}
const myString = makeSequenceString(10);
Or, more idiomatically, in some sort of pseudo-Haskell/ML/F# kind of syntax:
makeSequenceString top = (reduce (+) (map toString [1..top])) + "z"
myString = makeSequenceString 10
Note that the part that constructs the value is just one big expression, and the makeSequenceString
function does absolutely nothing but evaluate the expression and return its value. And since we're assigning that value immediately as part of the definition of myString
, there is no point in the program at which myString
is uninitialized or "being constructed" - as soon as it exists, it has a value, and that's the only value it will ever have (at least as long as the programmer sticks with a purely functional style).