Skip to content
Draft

Generics

Generics allow writing code that works with any type.

action identity<T>(@value: T) -> T
return @value
fin action.
@identity(42) @// Int
@identity("hello") @// String
action pair<A, B>(@first: A, @second: B) -> (A, B)
return (@first, @second)
fin action.
@result = pair(1, "one")
record Container<T>
value: T
fin record.
@int_container = Container<Int> { value: 42 }
@str_container = Container<String> { value: "hello" }
enum Option<T>
some(value: T)
none
fin enum.
enum Result<T, E>
ok(value: T)
err(error: E)
fin enum.

Constrain generics to specific types:

action print<T: Display>(@value: T)
write(@value#to_string())
fin action.
action process<T: Display + Clone>(@value: T)
@copy = @value#clone()
write(@copy#to_string())
fin action.
action sort<T: Comparable>(@items: Array<T>) -> Array<T>
return @items#sort()
fin action.

Complex constraints with where:

action process<T, U>(@input: T) -> U
where T: Display + Clone
U: From<T>
return U::from(@input)
fin action.
record Pair<A, B>
first: A
second: B
fin record.
impl<A, B> Pair<A, B>
action swap(@self: Pair<A, B>) -> Pair<B, A>
return Pair { first: @self#second, second: @self#first }
action fin.
fin impl.
impl<T: Display> Container<T>
action show(@self: Container<T>)
write(@self#value#to_string())
fin action.
fin impl.
trait Iterator
type Item
action next(@self: mut Iterator) -> Option<Self::Item>
fin trait.
impl Iterator for Counter
type Item = Int
action next(@self: mut Counter) -> Option<Int>
if @self#current < @self#max
@value = @self#current
@self#current = @self#current + 1
return some(@value)
fin if.
return none
fin action.
fin impl.
record Tagged<T, Tag>
value: T
fin record.
type Meters = Tagged<Float, "meters">
type Feet = Tagged<Float, "feet">

Draft infers generic types from usage:

@result = identity(42) @// T inferred as Int
@result = pair(1, "one") @// A inferred as Int, B as String
enum Option<T>
some(value: T)
none
fin enum.
enum Result<T, E>
ok(value: T)
err(error: E)
fin enum.
record Vec<T>
data: *T
length: Int
capacity: Int
fin record.
record HashMap<K, V>
buckets: Array<Array<(K, V)>>
size: Int
fin record.

Generics in Draft use monomorphization. Each concrete type generates specialized code at compile time with zero runtime overhead.