86 lines
2.7 KiB
Mojo
Generated
86 lines
2.7 KiB
Mojo
Generated
struct Span[mut: Bool, //, T: Copyable, origin: Origin[mut]]:
|
|
# ... implementation omitted
|
|
```
|
|
|
|
Here, the `mut` parameter is infer-only. The value is usually inferred when you
|
|
create an instance of `Span`. Binding the `mut` parameter by keyword lets you
|
|
define a `Span` that requires a mutable origin.
|
|
|
|
```mojo
|
|
def mutate_span(span: Span[mut=True, Byte, _]):
|
|
for i in range(0, len(span), 2):
|
|
if i + 1 < len(span):
|
|
span.swap_elements(i, i + 1)
|
|
```
|
|
|
|
If the compiler can't infer the value of an infer-only parameter, and it's not
|
|
specified by keyword, compilation fails.
|
|
|
|
## Parameter expressions are just Mojo code
|
|
|
|
A parameter expression is any code expression (such as `a+b`) that occurs where
|
|
a parameter is expected. Parameter expressions support operators and function
|
|
calls, just like run-time code, and all parameter types use the same type
|
|
system as the run-time program (such as `Int` and `DType`).
|
|
|
|
Because parameter expressions use the same grammar and types as run-time
|
|
Mojo code, you can use many
|
|
["dependent type"](https://en.wikipedia.org/wiki/Dependent_type) features. For
|
|
example, you might want to define a helper function to concatenate two SIMD
|
|
vectors:
|
|
|
|
```mojo
|
|
def concat[
|
|
dtype: DType, ls_size: Int, rh_size: Int, //
|
|
](lhs: SIMD[dtype, ls_size], rhs: SIMD[dtype, rh_size]) -> SIMD[
|
|
dtype, ls_size + rh_size
|
|
]:
|
|
var result = SIMD[dtype, ls_size + rh_size]()
|
|
|
|
comptime for i in range(ls_size):
|
|
result[i] = lhs[i]
|
|
|
|
comptime for j in range(rh_size):
|
|
result[ls_size + j] = rhs[j]
|
|
return result
|
|
```
|
|
|
|
Note that the resulting length is the sum of the input vector lengths, and a
|
|
simple `+` operation expresses this.
|
|
|
|
### Powerful compile-time programming
|
|
|
|
While simple expressions are useful, sometimes you want to write imperative
|
|
compile-time logic with control flow. You can even do compile-time recursion.
|
|
For instance, here is an example "tree reduction" algorithm that sums all
|
|
elements of a vector recursively into a scalar:
|
|
|
|
```mojo
|
|
def slice[
|
|
dtype: DType, size: Int, //
|
|
](x: SIMD[dtype, size], offset: Int) -> SIMD[dtype, size // 2]:
|
|
comptime new_size = size // 2
|
|
var result = SIMD[dtype, new_size]()
|
|
for i in range(new_size):
|
|
result[i] = Scalar[dtype](x[i + offset])
|
|
return result
|
|
|
|
|
|
def reduce_add(x: SIMD) -> Int:
|
|
comptime if x.length == 1:
|
|
return Int(x[0])
|
|
elif x.length == 2:
|
|
return Int(x[0]) + Int(x[1])
|
|
|
|
# Extract the top/bottom halves, add them, sum the elements.
|
|
comptime half_size = x.length // 2
|
|
var lhs = slice(x, 0)
|
|
var rhs = slice(x, half_size)
|
|
return reduce_add(lhs + rhs)
|
|
|
|
|
|
def main():
|
|
var x = SIMD[DType.int, 4](1, 2, 3, 4)
|
|
print(x)
|
|
print("Elements sum:", reduce_add(x))
|