nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.58k stars 1.47k forks source link

Distinct generic parameter types #1385

Open def- opened 10 years ago

def- commented 10 years ago
type intorfloat = int or float # Adding distinct doesn't help

proc x(a: intorfloat; b: intorfloat) =
  echo a, " ", b

# Working
proc y(a: int or float; b: int or float) =
  echo a, " ", b

var c: float = 2.0
var d: int = 3
x(c, d)

I would expect this code to work, but get a type mismatch:

foo.nim(11, 1) Error: type mismatch: got (float, int)
but expected one of: 
foo.x(a: intorfloat, b: intorfloat)

On a related note, maybe this is also supposed to work:

proc z[T1, T2: int or float](a: T1; b: T2) =
  echo a, " ", b

But it seems to suffer from the same problem.

oprypin commented 9 years ago

Got another example (seems more similar than I initially thought)

type
  A*[T] = distinct T
  B*[T] = distinct T

  AB*[T] = A[T] or B[T]

proc `==`*[T](x: distinct AB[T], y: distinct AB[T]): bool =
  true

var a: A[string]
var b: B[string]
assert(a == b)
(12, 9) Error: type mismatch: got (A[system.string], B[system.string])
but expected one of:
a0.==(x: distinct AB[==.T], y: distinct AB[==.T])
system.==(x: pointer, y: pointer)
etc etc
demotomohiro commented 3 years ago

This bug is still not fixed.

In Nim manual, there is following example code: https://nim-lang.org/docs/manual.html#generics-implicit-generics

proc p(a: Table, b: distinct Table)

# is roughly the same as:

proc p[Key, Value, KeyB, ValueB](a: Table[Key, Value], b: Table[KeyB, ValueB])

But this code results in compile error.

import tables

proc p(a: Table, b: distinct Table) =
  discard

proc p2[Key, Value, KeyB, ValueB](a: Table[Key, Value], b: Table[KeyB, ValueB]) =
  discard

var
  x: Table[int, string]
  y: Table[string, int]

# p2 works
p2(x, y)

# Compile error:
p(x, y)
/home/jail/prog.nim(17, 2) Error: type mismatch: got <Table[system.int, system.string], Table[system.string, system.int]>
but expected one of:
proc p(a: Table; b: distinct Table)
  first type mismatch at position: 2
  required type for b: CompositeTypeClass
  but expression 'y' is of type: Table[system.string, system.int]

expression: p(x, y)

Nim devel version:

Nim Compiler Version 1.5.1 [Linux: amd64]
Compiled at 2021-10-12
Copyright (c) 2006-2021 by Andreas Rumpf

git hash: 83128f217f63045974a48e61b65386abbfc97352
active boot switches: -d:release