Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nim. How to inherit all operations on distinct type?

Tags:

nim-lang

Suppose, I have type Radians = distinct float and type Degrees = distinct float
This is not allowing me to use all operations available for floats, even most basic arithmetics +, -, *
Is there any way to sort of 'inherit' them all and use distinct only for compile-time checks?

like image 241
IC_ Avatar asked Oct 29 '25 08:10

IC_


1 Answers

Check the Modeling Currencies section from the Distinct type on the nim manual for the full example.

In summary:

Use the borrow pragma

proc `*` (x: int, y: Dollar): Dollar {.borrow.}
proc `div` (x: Dollar, y: int): Dollar {.borrow.}

Use templates to reduce boilerplate

template multiplicative(typ, base: typedesc) =
  proc `*` *(x: typ, y: base): typ {.borrow.}
  proc `*` *(x: base, y: typ): typ {.borrow.}
  proc `div` *(x: typ, y: base): typ {.borrow.}
  proc `mod` *(x: typ, y: base): typ {.borrow.}
like image 193
hola Avatar answered Oct 31 '25 10:10

hola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!