Examples · wasi · 339 of 339
stats
A command-line tool with no JavaScript in it: build it for WASI, run it with wasmtime.
tin run examples/wasi/stats.tin// A command-line tool with no JavaScript in it: build it for WASI, run it with wasmtime.
//
// tin build examples/wasi/stats.tin --target wasi -o stats.wasm
// printf '3.5\n4\n10.25\n' | wasmtime run --env UNIT=kg stats.wasm
//
// It reads numbers from standard input until an empty line or the end of input,
// then prints a summary. `tin run examples/wasi/stats.tin` prints the same.
fn main() {
let unit = env("UNIT")
var values: float[] = []
var line = input("")
while line != "" {
match parseFloat(line) {
Some(v) => values.push(v),
None => print("skipping '{line}': not a number"),
}
line = input("")
}
if values.len == 0 {
print("no numbers")
return
}
var total = 0.0
var low = values[0]
var high = values[0]
for v in values {
total = total + v
if v < low { low = v }
if v > high { high = v }
}
let mean = total / float(values.len)
print("{values.len} values, mean {mean.fixed(2)}{unit}, min {low}{unit}, max {high}{unit}")
}