Skip to content

interop — examples

← all topics · 63 examples · page 2 of 2 · raw source ↓

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::ImportStatic_MathMax   topic: interop   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

using static "System.Math"

func run() -> double {
    return Max(2.5, 4.5)
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::JsonSerializer_Serialize   topic: interop   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test

using "System.Text.Json"

func run() -> string {
    return JsonSerializer.Serialize("hello")
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: TranspilerTests.cs::Transpiles_Import_Directive   topic: interop   status: verified
// compiles cleanly (no auto-run claim was extracted)

namespace Test
using "System.IO"
using "MyNamespace"

pub func run() {
    Console.WriteLine("hello")
}

wordcount

interop authored verified

Showcase example

// 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<K, V>

// ═════════════════════════════════════════════════════════════════════════════
// 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<string, int>`
// 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<string, int> {
    let counts = Dictionary<string, int>()
    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<string, int>, 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<string, int>) -> 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)
    }
}

Compiles

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests.cs::Bind_RefDataWithMethodsAndLambdas   topic: interop   status: unverified
// compiles cleanly (no auto-run claim was extracted)

namespace T
using "System.Net.Http"

data Config(name: string, url: string)
data Item(title: string, source: string)

ref data Aggregator {
    configs: List<Config>
    items: List<Item>
    client: HttpClient
    init() {
        self.configs = List<Config>()
        self.items = List<Item>()
        self.client = HttpClient()
    }
    func start() { self.poll() }
    func poll() {
        var tasks = List<Task<(List<Item>, List<string>)>>()
        for cfg in self.configs {
            let c = self.client
            let f = cfg
            tasks.Add(Task.Run(func() -> (List<Item>, List<string>) { return (List<Item>(), List<string>()) }))
        }
    }
    func query(filter: string, limit: int) -> List<Item> {
        var result = self.items
        if filter != "" { result = result.Where(func(n: Item) -> bool { return n.source == filter }).ToList() }
        return result.Take(limit > 0 ? limit : 50).ToList()
    }
    func count() -> int = self.items.Count
    func addConfig(name: string, url: string) = self.configs.Add(Config(name, url))
}

Runs `go` → 30

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_ExternalReflection.cs::Cast_ExplicitGenericArg_TypesElements   topic: interop   status: unverified
// verified behavior: Test.go(...) == 30

namespace Test
func go() -> int {
    let xs = List<object>()
    xs.Add(10)
    xs.Add(20)
    var sum = 0
    for n in xs.Cast<int>() {
        sum += n
    }
    return sum
}

Rejected at compile time: ES2151

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_ExternalReflection.cs::QualifiedExternalType_SilencesAmbiguity   topic: interop   status: unverified
// verified behavior: reports diagnostic ES2151

namespace Test
using "System.Threading"
using "System.Timers"
func go(t: System.Timers.Timer) -> double {
    return t.Interval
}

Runs `run` → 3

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::ChainedMember_JsonElement_GetArrayLength   topic: interop   status: unverified
// verified behavior: Test.run(...) == 3

namespace Test

using "System.Text.Json"

func run() -> int {
    let doc = JsonDocument.Parse("[10, 20, 30]")
    return doc.RootElement.GetArrayLength()
}

Runs `run` → 1

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::EnumLiteral_JsonValueKind_EmitsConstant   topic: interop   status: unverified
// verified behavior: Test.run(...) == 1

namespace Test

using "System.Text.Json"

func run() -> int {
    let kind = JsonValueKind.Object
    return kind == JsonValueKind.Object ? 1 : 0
}

Runs `run` → "6"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::ForIn_JsonEnumerateArray_GetProperty   topic: interop   status: unverified
// verified behavior: Test.run(...) == "6"

namespace Test

using "System.Text.Json"

func run() -> string {
    let doc = JsonDocument.Parse("[1, 2, 3]")
    let root = doc.RootElement
    var total = 0
    for el in root.EnumerateArray() {
        total += el.GetInt32()
    }
    return total.ToString()
}

Runs `run` → "object"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::JsonDocument_ChainedMemberAccess   topic: interop   status: unverified
// verified behavior: Test.run(...) == "object"

namespace Test

using "System.Text.Json"

func run() -> string {
    let doc = JsonDocument.Parse("{}")
    return doc.RootElement.ValueKind == JsonValueKind.Object ? "object" : "other"
}

Runs `run` → "object"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::JsonDocument_Parse_RootElement_ValueKind_Stepped   topic: interop   status: unverified
// verified behavior: Test.run(...) == "object"

namespace Test

using "System.Text.Json"

func run() -> string {
    let doc = JsonDocument.Parse("{}")
    let elem = doc.RootElement
    let kind = elem.ValueKind
    let isObj = kind == JsonValueKind.Object
    return isObj ? "object" : "other"
}

Runs `run` → "ok"

// E# — a verified example from the E# language corpus (CLR language; .es, not ECMAScript).
// provenance: ILEmitterTests_Interop.cs::OptionalStructParam_DefaultInitialized   topic: interop   status: unverified
// verified behavior: Test.run(...) == "ok"

namespace Test

using "System.Text.Json"

func run() -> string {
    let doc = JsonDocument.Parse("{}")
    return "ok"
}