String Builder Pattern
Demonstrates building strings with += (append) and concat.
Example 018 of the basic Soma programs: a small, commented program that teaches one thing. Every output below was printed by soma 3.2.4 when this page was built.
How it is built
The cell StringBuilder has no face and no memory. Handlers: run (line 18).
The source
018_string_builder.cell
// ============================================================================
// 018 — String Builder Pattern
// ============================================================================
// Demonstrates building strings with += (append) and concat.
//
// Run: soma run 018_string_builder.cell run
// Expect:
// CSV: name,age,city
// Alice,30,Paris
// Bob,25,London
// Carol,35,Tokyo
//
// Reversed: edcba
// Repeated: *****
cell StringBuilder {
on run() {
// += appends to a string
let csv = "name,age,city"
csv += "\nAlice,30,Paris"
csv += "\nBob,25,London"
csv += "\nCarol,35,Tokyo"
print("CSV: {csv}")
print("")
// Reversing a string character by character
let original = "abcde"
let reversed = ""
let i = len(original) - 1
while i >= 0 {
let ch = substring(original, i, i + 1)
reversed += ch
i = i - 1
}
print("Reversed: {reversed}")
// Repeating a character N times
let star = ""
let count = 0
while count < 5 {
star += "*"
count = count + 1
}
print("Repeated: {star}")
return "done"
}
}What the toolchain says
$ soma check 018_string_builder.cell
warning: `reversed` grows by concatenation inside a loop — each step copies the whole value, so the loop is quadratic (8 MB took 32 s, a list + join() 30 ms): push the pieces to a List and `join(parts, "")` once
--> 018_string_builder.cell:34:13
|
34 | reversed += ch
| ^
✓ 1 warning(s), no errors.$ soma run 018_string_builder.cell run
CSV: name,age,city
Alice,30,Paris
Bob,25,London
Carol,35,Tokyo
Reversed: edcba
Repeated: *****
done