with one click
with one click
Nim testing conventions, unittest framework, and C++ compatibility patterns
Nim bindings to libtorch for tensor operations with high-level sugar
Common import patterns and pitfalls for the Tattletale Nim project
Regex functionality in Nim including std/re, std/nre wrappers around PCRE, and the pure Nim nim-regex alternative with linear-time matching guarantees
Nim to Python interoperability including nimpy for calling Python from Nim and exporting Nim to Python, nimporter for packaging Nim modules as Python packages, and cffi/ctypes for calling Nim from Python
Nim's hash table module for key-value storage
| name | nim-type-system-faq |
| description | Nim type system patterns and pitfalls |
| license | MIT |
| compatibility | opencode |
| metadata | {"audience":"nim-developers","topic":"types"} |
When you define a generic with a union type like T: int|Nullopt_t, Nim requires ALL parameters of that type to be the SAME concrete type:
template handleNegativeIndex[T: int|Nullopt_t](idx: T, axisLen: int): T =
when idx is Nullopt_t:
idx
else:
if idx < 0:
idx + axisLen
else:
idx
This fails if you call handleNegativeIndex(start, len) where start is int and you want to pass nullopt for stop. The compiler complains because int and Nullopt_t are different types, even though both belong to the union.
distinct typeDefine a distinct wrapper type that "unifies" the union:
type OptInt* = distinct int | Nullopt_t
template handleNegativeIndex*[T: int|Nullopt_t](idx: T, axisLen: int): T =
when idx is Nullopt_t:
idx
else:
if idx < 0:
idx + axisLen
else:
idx
func normalizedSlice*(
start, stop: distinct OptInt,
step: OptInt = nullopt, axisLen: int): TorchSlice {.inline.} =
let normStart = handleNegativeIndex(start, axisLen)
let normStop = handleNegativeIndex(stop, axisLen)
torchSlice(normStart, normStop, step)
The distinct keyword creates a new type that:
option[T] from stdlib for explicit optional valuesnullopt singleton for "no value provided"when defined(T) branches for type-specific logic