Nim
Nim copied to clipboard
Too strong type bindings with multiple generic parameters
trafficstars
When a generic type has multiple generic parameters, it's not possible to instantiate types that share the same concrete type for the first generic parameter.
Example
import hashes, sets, tables
type
DEdge*[K, V] = ref object
fm*: DNode[K]
to*: DNode[K]
weight*: V
DNode*[K, V] = ref object
key*: K
DGraph*[K, V] = object
# A directed graph of nodes and directed edges
nodes: Table[K, DNode[K, V]]
proc add_edge*[K, V](graph: var DGraph[K, V], fm: K, to: K, weight: V = V(1)): DEdge[K, V] =
var n1 = DNode[K, V](key: fm)
var n2 = DNode[K, V](key: to)
result = DEdge[K, V](fm: n1, to: n2, weight: weight)
when true:
block:
var w = DGraph[int,int]()
let _ = w.add_edge(0, 1, 10)
echo w
block:
var g = DGraph[int,float]()
let _ = g.add_edge(3,4,3.5)
echo g
when defined(test2):
block:
var w = DGraph[int,int]()
let _ = w.add_edge(0, 1, 10)
echo w
block:
var g = DGraph[uint,float]()
let _ = g.add_edge(3u,4u,3.5)
echo g
Current Output
Building with -d:test1 yields:
Error: type mismatch: got <DNode[system.int, system.float]> but expected 'DNode[system.int, system.int]'
Expected Output
Building with -d:test2 works as expected.
Possible Solution
?
Additional Information
Per @mratsim : Nim type bindings rules are in-depth but unlike the examples given there your example is expected to work with the current Nim code.
https://forum.nim-lang.org/t/5640
% nim -v
Nim Compiler Version 1.0.4 [MacOSX: amd64]
Compiled at 2019-11-27
Copyright (c) 2006-2019 by Andreas Rumpf
git hash: c8998c498f5e2a0874846eb31309e1d1630faca6
active boot switches: -d:release