Pitch: Defining custom number types integers with bound ranges
- Dominant language
- Swift
- Stars
- 1.9k
- Forks
- 181
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 6
Description
It would be great to be able to work with (brand new shiny big) binary integers and using these to define bounded number types. Number bounded by range, e.g. a `BigInt` bound from `-273` to infinity, representing Kelvin.
I've given an attempt to do this in my [SPM Package "DelTal"](https://github.com/Sajjon/deltal).
```swift
/// `BUNCInt` is short _B_ound _U_nsigned _N_amed _C_ategorized _Int_eger
public typealias Kelvin = BUNCInt, KelvinName, Temperatur>
public struct KelvinName: IntegerName {
public static let nameOfInteger = "Kelvin"
}
public struct Temperatur: IntegerCategory {
public static let nameOfCategory = "Temperature"
}
public extension Kelvin {
enum Water {}
}
/* Verbose (needed) syntax for: `extension Kelvin.Water` */
public extension BUNCInt.Water where Name == KelvinName, Category == Temperatur {
static var meltsAt: Kelvin { .init(magnitude: 273) }
static var boilsAt: Kelvin { meltsAt + 100 }
}
```
It allows for expressive and safe [wrapping of primitives according to Object-Calisthenics rule #3](https://williamdurand.fr/2013/06/03/object-calisthenics/#3-wrap-all-primitives-and-strings), and fits perfectly with Swift philosophy of safety.
It would really be amazing if developers were able to get compile-time errors inline, just like, defining this overflowing `UInt8` yields a compile-time
```swift
let uint8: UInt8 = 1337
```
> Integer literal '1337' overflows when stored into 'UInt8'
Being able to get that for custom defined integer types (or `typealias`es) would be... awesome!
Contributor guide
Research direction
No repository files or tests are named. Start by evaluating the proposed bounded custom integer types and the compile-time overflow behavior shown for UInt8; done would require an agreed design and implementation scope for supporting these types.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- developer-experience
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100