Text Histogram
Build a simple text-based histogram from data.
Example 076 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 Histogram has no face and no memory. Handlers: run (line 16) and make_bar (line 55).
The source
076_histogram.cell
// ============================================================================
// 076 — Text Histogram
// ============================================================================
// Build a simple text-based histogram from data.
//
// Run: soma run 076_histogram.cell run
// Expect:
// Score Distribution:
// 0-59: **
// 60-79: ****
// 80-89: ***
// 90-100: *****
cell Histogram {
on run() {
let scores = list(45, 72, 88, 95, 67, 93, 82, 55, 91, 78, 85, 96, 63, 90)
// Count values in each bucket
let low = 0
let mid = 0
let high = 0
let top = 0
for s in scores {
if s < 60 {
low = low + 1
} else {
if s < 80 {
mid = mid + 1
} else {
if s < 90 {
high = high + 1
} else {
top = top + 1
}
}
}
}
print("Score Distribution:")
let b1 = make_bar(low)
let b2 = make_bar(mid)
let b3 = make_bar(high)
let b4 = make_bar(top)
print("0-59: {b1}")
print("60-79: {b2}")
print("80-89: {b3}")
print("90-100: {b4}")
return "done"
}
// Build a bar of asterisks
on make_bar(count: Int) {
let bar = ""
let i = 0
while i < count {
bar += "*"
i = i + 1
}
return bar
}
}What the toolchain says
$ soma check 076_histogram.cell
warning: `bar` 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
--> 076_histogram.cell:59:13
|
59 | bar += "*"
| ^
✓ 1 warning(s), no errors.$ soma run 076_histogram.cell run
Score Distribution:
0-59: **
60-79: ****
80-89: ***
90-100: *****
done