Files
pplus-library/mojo/corpus/manual/snippets/manual-parameters-index-4.mojo
alexm 568474d52f
Test (in pplus-core) / in-core (push) Failing after 28m44s
Initial commit
2026-11-12 22:23:48 -05:00

34 lines
1.2 KiB
Mojo
Generated

# Make a vector of 4 floats.
var small_vec = SIMD[DType.float32, 4](1.0, 2.0, 3.0, 4.0)
# Make a big vector containing 1.0 in float16 format.
var big_vec = SIMD[DType.float16, 32](1.0)
# Do some math and convert the elements to float32.
var bigger_vec = (big_vec + big_vec).cast[DType.float32]()
```
Note that the `cast()` method also needs a parameter to specify the type you
want from the cast (the method definition above expects a `target` parameter
value). Thus, just as the `SIMD` struct is a parameterized type definition, the
`cast()` method is a parameterized method definition. At compile time, the
compiler creates a concrete version of the `cast()` method with the target
parameter bound to `DType.float32`.
The code above shows the use of concrete types (that is, the parameters are all
bound to known values). But the major power of parameters comes from the ability
to define parameterized algorithms and types (code that uses the parameter
values). For example, here's how to define a parameterized algorithm with
`Scalar` that is datatype agnostic:
```mojo
from std.math import sqrt
def rsqrt[dt: DType](x: Scalar[dt]) -> Scalar[dt]:
return 1 / sqrt(x)
def main():
var v = Scalar[DType.float16](42)
print(rsqrt(v))