Analyze the Nim distinct type—how to prevent accidental addition of Dollars and Cents.
- User
Analyze the Nim
distincttype—how to prevent accidental addition ofDollarsandCents. Assistant
Analyze the Nim distinct type—how to prevent accidental addition of Dollars and Cents.
The user is asking about the Nim programming language, specifically regarding distinct types.
The core problem is preventing accidental addition of two distinct types (e.g., Dollars and Cents) which might share the same underlying type (e.g., int).
Key concepts to cover:
distinct keyword: What it does (creates a new type that is type-incompatible with its base type).distinct types lose the operators (like +, -) of the base type. But the user specifically asks how to prevent accidental addition. This implies that simply defining them isn't enough if one borrows operators blindly, or perhaps they want to know how to enforce the type safety so the compiler stops you.
Dollars = distinct int and Cents = distinct int, I cannot add them directly anyway because + isn't defined for them.dollar_var + cent_var?"Plan:
Dollars and Cents as distinct int.d + c fails to compile. This answers the "how to prevent" part—it's the default behavior!Dollars useful, you usually "borrow" the + operator from int.+, Dollars can be added to Dollars, but Dollars still cannot be added to Cents because they are distinct types.converter) and advise against it.borrow distinctively).Step-by-step Code Construction:
Definition:
type
Dollars = distinct int
Cents = distinct int
The "Prevention":
If I try var d = Dollars(10); var c = Cents(50); echo d + c, the compiler error is "type mismatch". This is exactly what the user wants.
The Nuance: The user might be thinking, "But they are both ints, won't Nim just treat them as ints?"
distinct explicitly breaks that link.Making them usable (but still safe):
We need to borrow + for Dollars and + for Cents.
proc `+`(x, y: Dollars): Dollars {.borrow.}
proc `+`(x, y: Cents): Cents {.borrow.}
Now Dollars(5) + Dollars(5) works.
But Dollars(5) + Cents(50) still fails. This demonstrates the solution.
Structure of the Response:
distinct provides this safety by default.{.borrow.} to enable math within the same unit, while maintaining the barrier between units.d.int * 100 + c.int) if you actually need to combine them, emphasizing that it must be manual.converter to int would break this safety, so avoid it.Refining the Content:
distinct works (type distinctness).{.borrow.} pragma, as that's the standard way to make distinct types usable without writing boilerplate, but strictly scoped to the specific type.Drafting the explanation:
distinct type creates a new type that is incompatible with its base type."Dollars(10) + Cents(50) is a compile-time error."Dollars(10) + Dollars(5), you must borrow the operator."Self-Correction during drafting: I should explicitly show the error message. It proves the point better than just saying "it errors".
Final Polish:
Let's write the response based on this structure.
In Nim, the distinct type is the primary mechanism for creating strong type aliases. Unlike a standard type alias (which is just a different name for the same type), a distinct type creates a completely new, incompatible type.
This effectively prevents accidental addition because the compiler treats the underlying data as completely different types, stripping away all built-in operators (+, -, *, etc.).
Here is an analysis of how to implement this, ranging from the strict default to ergonomic best practices.
By default, defining a distinct type makes it incompatible with its base type and other distinct types.
type
Dollars = distinct int
Cents = distinct int
let d = Dollars(10)
let c = Cents(50)
# Compile-time Error: type mismatch
let result = d + c
Why this fails:
+ operator defined for Dollars.d is type Dollars and c is type Cents. Nim's type system prevents mixing them.To make these types useful, you usually want to add Dollars to Dollars. You can do this by borrowing the + operator from the base type (int).
The .borrow. pragma tells the compiler: "Use the logic from the base type's implementation of this procedure."
type
Dollars = distinct int
Cents = distinct int
# Borrow '+' for Dollars
proc `+`(a, b: Dollars): Dollars {.borrow.}
# Borrow '+' for Cents
proc `+`(a, b: Cents): Cents {.borrow.}
var walletD = Dollars(10)
var changeD = Dollars(5)
var totalD = walletD + changeD # OK: Result is Dollars(15)
var walletC = Cents(100)
var changeC = Cents(50)
var totalC = walletC + changeC # OK: Result is Cents(150)
# Compile-time Error: Type mismatch: got (Dollars, Cents)
# This is the safety you asked for:
let error = walletD + changeC
Since you prevented accidental addition, you must explicitly define how to convert between them if you actually need to combine them (e.g., adding cents to a dollar amount).
You should not define an implicit converter, as that defeats the purpose of distinct types. Instead, define explicit procs or use distinct constructors.
# Explicit conversion logic
proc toCents(d: Dollars): Cents =
Cents(d.int * 100)
let price = Dollars(5)
let extra = Cents(50)
# Logic requires explicit intent
let total = price.toCents + extra
echo total.int # Output: 550
| Feature | Standard Alias (type MyInt = int) | Distinct Type (type MyInt = distinct int) |
|---|---|---|
| Type Compatibility | Interchangeable with base type | Incompatible with base and other distincts |
Operators (+, etc.) | Works immediately | Disabled by default |
| Mixing Types | Allowed (e.g., Dollars + Cents becomes int + int) | Blocked at compile time |
Nim allows you to define converters to bypass distinct type safety automatically.
# AVOID THIS if you want strict safety
converter toInt(d: Dollars): int = d.int
let d = Dollars(10)
let c = Cents(5)
# This would now compile, effectively breaking your safety net
# because the compiler implicitly converts both to 'int'.
let x = d + c
Conclusion: To prevent accidental addition, define your units as distinct. Borrow the operators you need for valid same-type arithmetic, and rely on the compiler to block cross-type interactions.