generics - nim 带有泛型的两个键表

标签 generics hashtable nim-lang

尝试在 Nim 中创建一个两键字典,其中值是用户指定的类型。

import Tables

type
  TwoKeyTable[T] = Table[string, Table[string, T]]

# initialize two key table
proc initTwoKeyTable[T](): TwoKeyTable[T] =
  result = initTable[string, Table[string, T]]()  

# check to see if keys k1 and k2 are in table
proc hasKeyPair[T](tkTable: TwoKeyTable[T], k1, k2: string): bool =
  result = false
  # check if first key is in table
  if not tkTable.hasKey(k1):
    return
  # check if second key in the tables
  if not tkTable[k1].hasKey(k2): # 1st error coming from here 
    return
  result = true

# add a value corresponding to the keys k1 and k2
proc addKeyPairValue[T](tkTable: var TwoKeyTable[T], k1, k2: string, val: T) =
  if not tkTable.hasKey(k1):
    tkTable[k1] = initTable[string, T]() # 2nd error coming from here
  tkTable[k1][k2] = val


var tkTable = initTwoKeyTable[int]()
echo tkTable.hasKeyPair("a", "b") # produces the 1st error

出现以下错误:

lib/pure/collections/tables.nim(249, 38) Error: type mismatch: got (Table[system.string, system.int]) but expected 'int

我也有这个问题。

var tkTable = initTwoKeyTable[int]()
tkTable.addKeyPairValue("a", "b", 1) # produces the 2nd error

这会产生相同的错误。

最佳答案

对我来说看起来很像一个错误,我报告了它:https://github.com/nim-lang/Nim/issues/2722

作为一种解决方法,当 TwoKeyTable 不是通用的时,它可以工作:

import Tables

type
  TwoKeyTable = Table[string, Table[string, int]]

# initialize two key table
proc initTwoKeyTable(): TwoKeyTable =
  result = initTable[string, Table[string, int]]()

# check to see if keys k1 and k2 are in table
proc hasKeyPair(tkTable: TwoKeyTable, k1, k2: string): bool =
  result = false
  # check if first key is in table
  if not tkTable.hasKey(k1):
    return
  # check if second key in the tables
  if not tkTable[k1].hasKey(k2): # 1st error coming from here
    return
  result = true

# add a value corresponding to the keys k1 and k2
proc addKeyPairValue[T](tkTable: var TwoKeyTable, k1, k2: string, val: T) =
  if not tkTable.hasKey(k1):
    tkTable[k1] = initTable[string, T]() # 2nd error coming from here
  tkTable[k1][k2] = val


var tkTable = initTwoKeyTable()
echo tkTable.hasKeyPair("a", "b") # produces the 1st error

关于generics - nim 带有泛型的两个键表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246999/

相关文章:

java - 创建类型对象的通用列表并添加字符串

使用 Emscripten 编译 Nim 和 SDL2 Image 时出现类型冲突

arrays - 尼姆 : advantage of using array over seq?

c - 如何动态地将新数据添加到二维数组?

nim-lang - Nim 中的反转字节和交叉兼容的二进制解析

c# - 返回子类实例的方法

java - 从 Scala 实现具有递归类型和边界的 Java 接口(interface)

c# - 将结构转换为通用接口(interface)时是否有装箱/拆箱?

swift - 引用作为 swift 字典中的键

c++ - 删除动态内存