Add full support for user-defined generic types and functions: - Add type_params field to TypeChecker to track type parameters in scope - Update resolve_type() to resolve type parameters to their bound variables - Update function_type() to bind type parameters and return polymorphic TypeScheme - Update type declaration handling for generic ADTs (e.g., Pair<A, B>) Generic functions and types now work: fn identity<T>(x: T): T = x type Pair<A, B> = | MkPair(A, B) fn first<A, B>(p: Pair<A, B>): A = ... Add examples/generics.lux demonstrating: - Generic identity function - Generic Pair type with first/second accessors - Generic mapOption function Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
62 lines
1.4 KiB
Plaintext
62 lines
1.4 KiB
Plaintext
// Demonstrating generic type parameters in Lux
|
|
//
|
|
// Expected output:
|
|
// identity(42) = 42
|
|
// identity("hello") = hello
|
|
// first(MkPair(1, "one")) = 1
|
|
// second(MkPair(1, "one")) = one
|
|
// map(Some(21), double) = Some(42)
|
|
|
|
// Generic identity function
|
|
fn identity<T>(x: T): T = x
|
|
|
|
// Generic pair type
|
|
type Pair<A, B> =
|
|
| MkPair(A, B)
|
|
|
|
fn first<A, B>(p: Pair<A, B>): A =
|
|
match p {
|
|
MkPair(a, _) => a
|
|
}
|
|
|
|
fn second<A, B>(p: Pair<A, B>): B =
|
|
match p {
|
|
MkPair(_, b) => b
|
|
}
|
|
|
|
// Generic map function for Option
|
|
fn mapOption<T, U>(opt: Option<T>, f: fn(T): U): Option<U> =
|
|
match opt {
|
|
None => None,
|
|
Some(x) => Some(f(x))
|
|
}
|
|
|
|
// Helper function for testing
|
|
fn double(x: Int): Int = x * 2
|
|
|
|
// Test usage
|
|
let id_int = identity(42)
|
|
let id_str = identity("hello")
|
|
|
|
let pair = MkPair(1, "one")
|
|
let fst = first(pair)
|
|
let snd = second(pair)
|
|
|
|
let doubled = mapOption(Some(21), double)
|
|
|
|
fn showOption(opt: Option<Int>): String =
|
|
match opt {
|
|
None => "None",
|
|
Some(x) => "Some(" + toString(x) + ")"
|
|
}
|
|
|
|
fn printResults(): Unit with {Console} = {
|
|
Console.print("identity(42) = " + toString(id_int))
|
|
Console.print("identity(\"hello\") = " + id_str)
|
|
Console.print("first(MkPair(1, \"one\")) = " + toString(fst))
|
|
Console.print("second(MkPair(1, \"one\")) = " + snd)
|
|
Console.print("map(Some(21), double) = " + showOption(doubled))
|
|
}
|
|
|
|
let output = run printResults() with {}
|