Parametric polymorphism in Odin
One largest() for ints and floats: $T takes the element type at compile time.
package main
import "core:fmt"
// $T takes the element type at compile time -- parametric polymorphism.
largest :: proc(items: []$T) -> T {
best := items[0]
for x in items[1:] {
if x > best do best = x
}
return best
}
main :: proc() {
ints := []int{3, 41, 12, 55}
floats := []f64{2.5, 8.75, 1.25}
fmt.println("largest int:", largest(ints))
fmt.println("largest float:", largest(floats))
}
How it works
items: []$Tbinds the slice's element type toTper call site.- The body compares with
>; each instantiation checks it for its own T. largest(ints)andlargest(floats)compile to two separate procedures.
Keywords and builtins used here
Tdof64forifimportinintpackageprocreturn
The run, in numbers
- Lines
- 19
- Characters to type
- 391
- Tokens
- 106
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 98 seconds.
Step 2 of 3 in Types & generics, step 20 of 27 in Language basics.