https://github.com/alaviss/union
Anonymous unions in Nim
https://github.com/alaviss/union
Last synced: 8 months ago
JSON representation
Anonymous unions in Nim
- Host: GitHub
- URL: https://github.com/alaviss/union
- Owner: alaviss
- License: mit
- Created: 2021-09-09T22:56:15.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2024-02-07T21:37:53.000Z (over 1 year ago)
- Last Synced: 2024-12-28T17:53:23.189Z (9 months ago)
- Language: Nim
- Size: 123 KB
- Stars: 56
- Watchers: 4
- Forks: 2
- Open Issues: 2
-
Metadata Files:
- Readme: readme.md
- License: license.txt
Awesome Lists containing this project
README
# An implementation of anonymous unions in Nim
[](https://github.com/alaviss/union/actions?query=workflow%3ACI)

[](#license)- [API documentation][0]
## Example
```nim
import uniontype None = object
## A type for not having any dataproc search[T, U](x: T, needle: U): union(U | None) =
# Assignment can be done via explicit conversion
result = None() as union(U | None)let idx = find(x, needle)
if idx >= 0:
# Or the `<-` operator which automatically converts the type
result <- x[idx]assert [1, 2, 42, 20, 1000].search(10) of None
assert [1, 2, 42, 20, 1000].search(42) as int == 42
# For `==`, no explicit conversion is necessary
assert [1, 2, 42, 20, 1000].search(42) == 42
# Types that are not active at the moment will simply be treated as not equal
assert [1, 2, 42, 20, 1000].search(1) != None()proc `{}`[T](x: seq[T], idx: Natural): union(T | None) =
## An array accessor for seq[T] but doesn't raise if the index is not there
# Using makeUnion, an expression may return more than one type
makeUnion:
if idx in 0 ..< x.len:
x[idx]
else:
None()assert @[1]{2} of None
assert @[42]{0} == 42import json
# With unpack(), dispatching based on the union type at runtime is possible!
var x = 42 as union(int | string)block:
let j =
unpack(x):
# The unpacked variable name is `it` by default
%itassert j.kind == JInt
x <- "string"
block:
let j =
# You can give the unpacked variable a different name via the second
# parameter, too.
unpack(x, upk):
%upkassert j.kind == JString
```See the [documentation][0] for more information on features and limitations of
this module## License
This project is distributed under the terms of the MIT license.
See [license.txt](license.txt) for more details.
[0]: https://alaviss.github.io/union