sample-code: Add demo for get_line()

This commit is contained in:
John 2025-01-28 06:56:30 -06:00
parent 86c4da0689
commit 678c0f952c

44
sample-code/letter_frequency.cl Executable file
View File

@ -0,0 +1,44 @@
#!/usr/bin/env -S conlang -r false
// Showcases `get_line` behavior by sorting stdin
fn in_range(this: Ord, min: Ord, max: Ord) -> bool {
min < this && this < max
}
fn frequency(s: str) -> [i32; 128] {
let letters = [0;128];
for letter in s {
if (letter).in_range(' ', letters.len() as char) {
letters[(letter as i32)] += 1;
}
}
letters
}
fn plot_freq(freq: [i32; 128]) -> str {
let buf = "";
for idx in 0..len(freq) {
for n in 0..(freq[idx]) {
buf += idx as char;
}
}
buf
}
const msg: str ="letter_frequency.cl
Computes the frequency of ascii characters in a block of text, and prints it bucket-sorted.
Press Ctrl+D to quit.";
fn main () {
println(msg)
let lines = "";
loop {
let line = get_line();
if line == "" { break() }
lines += line;
}
let freq = frequency(lines)
let plot = plot_freq(freq)
println(plot)
}