iTranslated by AI
Type Representation Using Constant Expressions in Onyx
In Onyx, the where token is used when specifying interfaces in function definitions. While you can list multiple interfaces in a where clause separated by commas, it is also possible to write constant expressions instead of interfaces. I find this to be a very interesting feature, yet it is mentioned surprisingly briefly in the documentation.
Where expressions
Compile-time constant expressions can be used alongside interfaces in
whereclauses. This gives the programmer even more control over the conditions their function will be called under. For example, ensuring the length of an array fits within a specific range allows us to optimize our code.
Here is sample code for a function that "takes an array with an even number of elements, calculates the sum of each pair (combining two into one), and returns an array with half the number of elements of the original array".
use core {*}
// Expressing in the type that the input array has an even number of elements and the return value has half that length
add_pairs :: (arr: [$N] $T) -> [N/2] T where N % 2 == 0 {
ret: [N/2] T;
for i: 0 .. N {
if i % 2 == 1 do continue;
ret[i/2] = arr[i] + arr[i+1];
}
return ret;
}
main :: () {
println(add_pairs(i32.[ 1, 2, 3, 4 ])); // => [ 3, 7 ]
// println(add_pairs(i32.[ 1, 2, 3 ])); // => Compile Error
}
If you pass an array with an odd number of elements, it correctly results in a compilation error.
$ onyx run src/where.onyx
(/xxxxx/src/where.onyx:4,52) Where clause did not evaluate to true.
4 | add_pairs :: (arr: [$N] $T) -> [N/2] T where N % 2 == 0 {
^~
(/xxxxx/src/where.onyx:15,22) Here is the code that caused this constraint to be checked.
15 | println(add_pairs(i32.[ 1, 2, 3 ])); //=> Compile Error
^
In terms of classification, is this a feature similar to dependent types in languages like Idris (I don't know much about it and haven't researched it)?
Or is this kind of type expression common in other languages like C++, Java, or TypeScript?
Supplementary Note
The sample code in this article will not work unless you use the nightly build (as of 2023-12-29, v0.1.8).
To install the nightly build, simply add nightly to the end of the installation command.
sh <(curl https://get.onyxlang.io -sSfL) nightly
Discussion