Skip to content

proposal (with implementation): undistinct(T) #8519

Closed
@timotheecour

Description

@timotheecour
type A=distinct int

proc test()=
  let a1:A = 0.A
  let a2:A = 0.A

  when defined(case0):
    # ok but verbose and not DRY
    echo a1.int == a2.int

  when defined(case1):
    # Error: type mismatch: got <A, A>
    echo a1 == a2

  when defined(case2):
    # ok but requires boilerplate
    proc `==`(a:A, b:A):bool = a.int == b.int
    echo a1 == a2

  when defined(case2b):
    # ok but requires boilerplate (a tiny bit less)
    proc `==`(a:A, b:A):bool {.borrow.}
    echo a1 == a2

  when defined(case3):
    # BUG: not matched (how to do that?) ; should be in system.nim
    proc `==`[T](a:distinct T, b:distinct T): bool = a.T == b.T
    echo a1 == a2

test()

redefining == for distinct int (more generally distinct T for any type T) doesn't make much sense, it's just boilerplate.

so the proposal is:

  • add undistinct(T) such that type T2 = distinct T; assert T2.undistinct is T
  • add this to system.nim or some stdlib module EDIT removed from this proposal after feedback
proc `==`[T:distinct](a:T, b:T): bool =
  type T2 = T.undistinct
  a.T2 == b.T2

NOTE: https://nim-lang.org/docs/manual.html#type-relations-type-equality-modulo-type-distinction suggests using a.baseType but that doesn't work

EDIT see my reply below for a working implementation

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions