// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript). // provenance: wordcount.es topic: interop status: verified // hand-authored, idiomatic E# — verified through the E# compiler namespace Demo using "System.Collections.Generic" // Dictionary // ═════════════════════════════════════════════════════════════════════════════ // Counting word frequencies — a tour of BCL interop, which is the soul of E#. // // There is no bespoke E# hash map: you reach straight for `Dictionary` // from the .NET base class library and call it directly — `ContainsKey`, the `[key]` // indexer for get and set, `Count`, `TryGetValue` with an `out` parameter. E# adds no // wrapper; a `Dictionary` here is the same `Dictionary` a C# caller would hand you. // `string.Split`, `.ToLower()`, and `.Length` are likewise just the BCL string API. // // The program reads a sentence, tallies each word, then finds the most frequent one // — a single pass to count, a single pass to pick the winner. `out` is the idiomatic // BCL "return a bool and a value" shape, and E# speaks it natively (`out var n`). // ═════════════════════════════════════════════════════════════════════════════ // Tally how many times each (lower-cased) word appears. Returns the populated map. func tally(text: string) -> Dictionary { let counts = Dictionary() let words = text.ToLower().Split(' ') var i = 0 while i < words.Length { let w = words[i] if w.Length > 0 { // get-or-zero then store back: the indexer reads and writes the same cell. if counts.ContainsKey(w) { counts[w] = counts[w] + 1 } else { counts[w] = 1 } } i += 1 } return counts } // How many times one word occurs, using the BCL `TryGetValue(key, out value)` pattern. // `out n` binds a fresh local the call fills; reading `n` afterward is the count (or 0 // when the word is absent and the call returned false). func frequency(counts: Dictionary, word: string) -> int { if counts.TryGetValue(word, out var n) { return n } return 0 } // Walk the entries to find the highest count. `for (k, v) in dict` destructures each // KeyValuePair into its key and value — tuple-style iteration over a BCL collection. func mostFrequentCount(counts: Dictionary) -> int { var best = 0 for (word, n) in counts { if n > best { best = n } } return best } // "the cat sat on the mat the cat ran" — "the" appears 3×, "cat" 2×, rest once. // frequency("the") is 3; the single most-frequent count is also 3. 3 + 3 = 6. // // The driver is a `main` method on a `ref data Program` — the class-style program. That // method IS the entry point; the compiler constructs the program (`Program()`) and calls // `.main()`, so no separate launcher function is needed. ref data Program { func main() -> int { let counts = tally("the cat sat on the mat the cat ran") return frequency(counts, "the") + mostFrequentCount(counts) } }