From 678c0f952c1e9d2ee7eca6db8644eb73c859db17 Mon Sep 17 00:00:00 2001 From: John Date: Tue, 28 Jan 2025 06:56:30 -0600 Subject: [PATCH] sample-code: Add demo for get_line() --- sample-code/letter_frequency.cl | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100755 sample-code/letter_frequency.cl diff --git a/sample-code/letter_frequency.cl b/sample-code/letter_frequency.cl new file mode 100755 index 0000000..f42b893 --- /dev/null +++ b/sample-code/letter_frequency.cl @@ -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) +}