mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 00:44:27 +00:00
- fn Struct.method(...) with self by reference, also on C structs
- map[K]V: insertion-ordered hash maps, literals, m[k] += 1, has/get/remove/keys/values
- -> T! / -> !, return error(...), or <value>, or { err }, try; fallible int/float/read_file/write_file/delete_file
- for i, x in list / for k, v in map
- print and str() share one text formatter
- LSP: method and map completion, method signatures; grammar and snippets for VS Code and Kate
- tests: 74 (methods, errors, maps + 11 failure cases); docs at all three levels, en and pl
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
62 lines
1.5 KiB
Text
62 lines
1.5 KiB
Text
// Counts the words in a file: maps, methods and errors as values.
|
|
// finch run examples/wordcount.fch README.md
|
|
|
|
struct Counter {
|
|
map[str]int counts
|
|
int total
|
|
}
|
|
|
|
// lower-case letters and digits only: "Hello," -> "hello"
|
|
fn clean(str word) -> str {
|
|
out := ""
|
|
for c in word.lower() {
|
|
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') {
|
|
out += str(c)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
fn Counter.add(str text) {
|
|
for word in text.split(" ") {
|
|
w := clean(word)
|
|
if w.len > 0 {
|
|
self.counts[w] += 1 // a new word starts at 0
|
|
self.total += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
// the n most frequent words, most frequent first
|
|
fn Counter.top(int n) -> []str {
|
|
words := self.counts.keys()
|
|
for i in 0..words.len {
|
|
for j in i + 1..words.len {
|
|
if self.counts[words[j]] > self.counts[words[i]] {
|
|
w := words[i]
|
|
words[i] = words[j]
|
|
words[j] = w
|
|
}
|
|
}
|
|
}
|
|
if words.len > n {
|
|
words.resize(n)
|
|
}
|
|
return words
|
|
}
|
|
|
|
fn main([]str args) -> ! {
|
|
if args.len < 2 {
|
|
return error("usage: wordcount <file>")
|
|
}
|
|
text := try read_file(args[1]) // a missing file ends the program with a clear message
|
|
|
|
Counter c
|
|
for line in text.split("\n") {
|
|
c.add(line)
|
|
}
|
|
print(c.total, "words,", c.counts.len, "different")
|
|
for i, w in c.top(10) {
|
|
print(i + 1, w, c.counts[w])
|
|
}
|
|
}
|