Generics
In a lot of cases, you want code to be generic over many different types, therefore both types and units support generic parameters.
Defining Generics
Units and types which are generic have their generic parameters specified inside angle brackets (<>) after their name. Generic parameters come in either of two flavors, type variables and compile-time values. In the body of the generic item, the generic parameters are referred to by their names.
The type variables, usually denoted by upper-case letters like T, U, etc are placeholders for specific but currently unknown types. A good, simple example of this is Option<T> which can, optionally, contain an arbitrary value of type T:
enum Option<T> {
Some{val: T},
None,
}Compile-time values on the other hand are values (and not types!) which are known at compile-time. As generic parameters they are defined like #type N where type is the type of the value and N its name. Common cases for the type type are uint, int or bool.
For example a struct storing an array of arbitrary length N and element type T is defined as:
struct ContainsArray<T, #uint N> {
inner: [T; N]
}Note the use of uint here for defining a compile-time non-negative integer N.
Using Generics
When specifying generic parameters, angle brackets (<>) are also used. For example, a function which takes a ContainsArray with 5 8-bit integers is defined as:
Functions together with Entities together with fn and Defines a pipeline. The number in in the parentheses is input-to-output latency of the pipeline. are the basic building blocks of Spade circuits. Unlike fn, entity can contain registers and therefore have state and unlike Defines a pipeline. The number in in the parentheses is input-to-output latency of the pipeline., they do not have a statically known latency or Defines a pipeline. The number in in the parentheses is input-to-output latency of the pipeline. structure. and Defines a pipeline. The number in in the parentheses is input-to-output latency of the pipeline. are the basic building blocks of Spade circuits. Unlike entities and pipelines, functions have no internal state, they are combinational (pure). takes_array(a: ContainsArray<Type used to represent signed integers. The generic parameter (<N>) specReturns the value of the first branch if the condition is true, otherwise the second branch.
Note that unlike software languages, Spade does not have conditional execution. You do not conditionally assign values inside if expressiosn, you compute a value and return it.ies the number of bits, 5>) {
...
}