【问题标题】:any types in tables/table-like sets in nimnim 中的表/类表集合中的任何类型
【发布时间】:2016-06-30 21:17:52
【问题描述】:

如何使表格在 Nim 中具有任何类型的键和值?例如,下面的代码不起作用:

{"a": "string", "b": 4}

它说它期望 (string, string) 但得到 (string, int),这意味着类型是从第一个元组确定的。由于泛型中不允许使用 any 类型,我该如何使其工作?

【问题讨论】:

    标签: dictionary nim-lang


    【解决方案1】:

    您可以使用以下方法(取自 json 模块):

    import hashes, tables
    
    type MyTypeKinds = enum
        MNil, MInt, MString
    
    type MyGenericType = object
      case kind*: MyTypeKinds
    
      of MString:
        str*: string
    
      of MInt:
        num*: BiggestInt
    
      of MNil:
        nil
    
    proc hash(mg: MyGenericType): Hash =
      case mg.kind:
      of MString:
        result = hash(mg.str)
      of MInt:
        result = hash(mg.num)
      of MNil:
        result = hash(0)
    
    proc `==`(a: MyGenericType, b: MyGenericType): bool =
      if a.kind != b.kind:
        return false
      case a.kind:
      of MString:
        return a.str == b.str
      of MInt:
        return a.num == b.num
      of MNil:
        return true
    
    var genericTable = initTable[MyGenericType, MyGenericType]()
    
    var key, val: MyGenericType
    
    key.kind = MString
    key.str = "a"
    
    val.kind = MInt
    val.num = 4
    
    genericTable[key] = val
    
    echo genericTable[key].num
    

    为了更好的可读性,您可能需要实现类似 json 的 % operator

    这样你仍然不能使用任何类型,只能使用一组预定义的类型,但这没关系,因为表要求类型具有哈希过程。

    编辑:通过添加比较过程并修复拼写错误使代码成功编译

    【讨论】:

      【解决方案2】:
      #it is already in language core  : 
      var Python_like_dic: openArray[(string, string)] = {"a": "string", "b": 4}
      
      
      #iterations : 
      for i in Python_like_dic : 
          echo i[0] , " = " , i[1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多