Skip to content

Commit 8495524

Browse files
Tokazamacscherrer
andauthored
Document static traits (#182) (#184)
* Document static traits * Update docs/src/index.md Co-authored-by: Chad Scherrer <[email protected]> * Clarify appropriate use case of size Co-authored-by: Chad Scherrer <[email protected]>
1 parent 2c1fcbb commit 8495524

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/src/index.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,41 @@ CurrentModule = ArrayInterface
1111
Modules = [ArrayInterface]
1212
```
1313

14+
## Static Traits
15+
16+
The size along one or more dimensions of an array may be known at compile time.
17+
`ArrayInterface.known_size` is useful for extracting this information from array types and `ArrayInterface.size` is useful for extracting this information from an instance of an array.
18+
For example:
19+
20+
```julia
21+
julia> a = ones(3)';
22+
23+
julia> ArrayInterface.size(a)
24+
(static(1), 3)
25+
26+
julia> ArrayInterface.known_size(typeof(a))
27+
(1, nothing)
28+
29+
```
30+
31+
This is useful for dispatching on known information about the size of an array:
32+
```julia
33+
fxn(x) = _fxn(ArrayInterface.size(x), x)
34+
_fxn(sz::Tuple{StaticInt{S1},StaticInt{S2}}, x) where {S1,S2} = ...
35+
_fxn(sz::Tuple{StaticInt{3},StaticInt{3}}, x) = ...
36+
_fxn(sz::Tuple{Int,StaticInt{S2}}, x) where {S2} = ...
37+
_fxn(sz::Tuple{StaticInt{S1},Int}, x) where {S1} = ...
38+
_fxn(sz::Tuple{Int,Int}, x) = ...
39+
```
40+
41+
Methods should avoid forcing conversion to static sizes when dynamic sizes could potentially be returned.
42+
Fore example, `fxn(x) = _fxn(Static.static(ArrayInterface.size(x)), x)` would result in dynamic dispatch if `x` is an instance of `Matrix`.
43+
Additionally, `ArrayInterface.size` should only be used outside of generated functions to avoid possible world age issues.
44+
45+
Generally, `ArrayInterface.size` uses the return of `known_size` to form a static value for those dimensions with known length and only queries dimensions corresponding to `nothing`.
46+
For example, the previous example had a known size of `(1, nothing)`.
47+
Therefore, `ArrayInterface.size` would have compile time information about the first dimension returned as `static(1)` and would only look up the size of the second dimension at run time.
48+
Generic support for `ArrayInterface.known_size` relies on calling `known_length` for each type returned from `axes_types`.
49+
Therefore, the recommended approach for supporting static sizing in newly defined array types is defining a new `axes_types` method.
50+
51+
Static information related to subtypes of `AbstractRange` include `known_length`, `known_first`, `known_step`, and `known_last`.

0 commit comments

Comments
 (0)