tmapconcept.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. discard """
  2. output: '''10
  3. 10
  4. 1'''
  5. nimout: '''
  6. K=string V=int
  7. K=int64 V=string
  8. K=int V=int
  9. '''
  10. """
  11. import tables, typetraits
  12. template ok(check) = assert check
  13. template no(check) = assert(not check)
  14. type
  15. Enumerable[T] = concept e
  16. for v in e:
  17. v is T
  18. Map[K, V] = concept m, var mvar
  19. m[K] is V
  20. mvar[K] = V
  21. m.contains(K) is bool
  22. m.valuesSeq is Enumerable[V]
  23. TreeMap[K, V] = object
  24. root: int
  25. SparseSeq = object
  26. data: seq[int]
  27. JudyArray = object
  28. data: SparseSeq
  29. static:
  30. ok seq[int] is Enumerable[int]
  31. ok seq[string] is Enumerable
  32. ok seq[int] is Enumerable[SomeNumber]
  33. ok SparseSeq.data is Enumerable
  34. no seq[string] is Enumerable[int]
  35. no int is Enumerable
  36. no int is Enumerable[int]
  37. # Complete the map concept implementation for the Table type
  38. proc valuesSeq[K, V](t: Table[K, V]): seq[V] =
  39. result = @[]
  40. for k, v in t:
  41. result.add v
  42. # Map concept inplementation for TreeMap
  43. proc valuesSeq(t: TreeMap): array[1, TreeMap.V] =
  44. var v: t.V
  45. result = [v]
  46. proc contains[K, V](t: TreeMap[K, V], key: K): bool = true
  47. proc `[]=`[K, V](t: var TreeMap[K, V], key: K, val: V) = discard
  48. proc `[]`(t: TreeMap, key: t.K): TreeMap.V = discard
  49. # Map concept implementation for the non-generic JudyArray
  50. proc valuesSeq(j: JudyArray): SparseSeq = j.data
  51. proc contains(t: JudyArray, key: int): bool = true
  52. proc `[]=`(t: var JudyArray, key, val: int) = discard
  53. proc `[]`(t: JudyArray, key: int): int = discard
  54. iterator items(s: SparseSeq): int =
  55. for i in s.data: yield i
  56. # Generic proc defined over map
  57. proc getFirstValue[K,V](m : Map[K,V]): V =
  58. static: echo "K=", K.name, " V=", V.name
  59. for i in m.valuesSeq:
  60. return i
  61. raise newException(RangeDefect, "no values")
  62. proc useConceptProcInGeneric[K, V](t: Table[K, V]): V =
  63. return t.getFirstValue
  64. var t = initTable[string, int]()
  65. t["test"] = 10
  66. echo t.getFirstValue
  67. echo t.useConceptProcInGeneric
  68. var tm = TreeMap[int64, string](root: 0)
  69. echo getFirstValue(tm)
  70. var j = JudyArray(data: SparseSeq(data: @[1, 2, 3]))
  71. echo getFirstValue(j)
  72. static:
  73. ok Table[int, float] is Map
  74. ok Table[int, string] is Map[SomeNumber, string]
  75. no JudyArray is Map[string, int]