mirror of
https://github.com/Nexoniarz/Finch.git
synced 2026-11-03 00:44:27 +00:00
Finch 2.4.0: methods, maps, errors as values; str() of any value; macOS and ARM64 docs; Kate support
- 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>
This commit is contained in:
parent
fd86eb885c
commit
b872be3176
55 changed files with 3400 additions and 336 deletions
62
examples/wordcount.fch
Normal file
62
examples/wordcount.fch
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// 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])
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue