Hi all. Playing with nim. I can not understand whether it is possible to specify both a distinct type and subrange? How can it be done beautifully? I do so
type float_range = range[0.0 .. 1.0]
type DAC = distinct float_range
proc print(x: varargs[DAC]) =
for i in items x:
echo i.float
proc `+`(x, y: DAC): DAC =
result = DAC(float_range(x) + float_range(y))
let a : DAC = (0.5).DAC + 0.2.DAC
a.print
I would like the Ada's semantics - type XXX is float range 0.0 .. 1.0distinct range works. I use this for my go game bot.
type
################################ Coordinates ###################################
GoInt* = int32 # Easily switch the base int type for perf testing. 2 concerns are competing:
# - native word size so that there is no zero-extend/convert for register moves and array accesses
# - Cache locality: If data can stay in L1 cache it's much better and smaller data: easier to move.
# Should be int16 minimum (int8/uint8 can only represent 128/256 values)
GoInt2* = uint32 # We use graph theory "Sum of square of vertex degrees" to speedily determine atari
# Should be uint32 or int64 minimum (rollover is fine)
GoNatural* = range[0.GoInt .. high(GoInt)]
GoNatural2* = range[0.GoInt2 .. high(GoInt2)]
# We index from 0
Coord*[N: static[GoInt]] = tuple[col, row: range[0.GoInt .. (N-1)]]
Point*[N: static[GoInt]] = distinct range[-1.GoInt .. (N+2) * (N+2) - 1]
# -1 is used for ko or group position: nil
# Can't use plain static[GoInt]: https://github.com/nim-lang/Nim/issues/7609
it would be good to have syntax like
type XXX = distinct float of range[0.0 .. 1.0]
or
type XXX = distinct range[0.0 .. 1.0] of float
so we can implement operations for a new type like
proc `+`(a, b: XXX): XXX {.borrow.}
to borrow operation routine for base type with bounds checking of rangeI could extend the code example of @mratsim
to have
type
GN* = distinct GoNatural
GN2* = distinct GoNatural2
var
myGN: GN = GN(23)
It is probably useful for the base type of you distinct type to be named, for a type like
type XXX = distinct range[0.0 .. 1.0] of float
Else you will be typing a lot of
range[0.0 .. 1.0] of float
in your code