tgeneric0.nim 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. discard """
  2. output: '''
  3. 100
  4. 0
  5. '''
  6. """
  7. import tables
  8. block tgeneric0:
  9. type
  10. TX = Table[string, int]
  11. proc foo(models: seq[Table[string, float]]): seq[float] =
  12. result = @[]
  13. for model in models.items:
  14. result.add model["foobar"]
  15. # bug #686
  16. type TType[T; A] = array[A, T]
  17. proc foo[T](p: TType[T, range[0..1]]) =
  18. echo "foo"
  19. proc foo[T](p: TType[T, range[0..2]]) =
  20. echo "bar"
  21. #bug #1366
  22. proc reversed(x: auto) =
  23. for i in countdown(x.low, x.high):
  24. echo i
  25. reversed(@[-19, 7, -4, 6])
  26. block tgeneric1:
  27. type
  28. TNode[T] = tuple[priority: int, data: T]
  29. TBinHeap[T] = object
  30. heap: seq[TNode[T]]
  31. last: int
  32. PBinHeap[T] = ref TBinHeap[T]
  33. proc newBinHeap[T](heap: var PBinHeap[T], size: int) =
  34. new(heap)
  35. heap.last = 0
  36. newSeq(heap.heap, size)
  37. #newSeq(heap.seq, size)
  38. proc parent(elem: int): int {.inline.} =
  39. return (elem-1) div 2
  40. proc siftUp[T](heap: PBinHeap[T], elem: int) =
  41. var idx = elem
  42. while idx != 0:
  43. var p = parent(idx)
  44. if heap.heap[idx].priority < heap.heap[p].priority:
  45. swap(heap.heap[idx], heap.heap[p])
  46. idx = p
  47. else:
  48. break
  49. proc add[T](heap: PBinHeap[T], priority: int, data: T) =
  50. var node: TNode[T]
  51. node.priority = priority
  52. node.data = data
  53. heap.heap[heap.last] = node
  54. siftUp(heap, heap.last)
  55. inc(heap.last)
  56. proc print[T](heap: PBinHeap[T]) =
  57. for i in countup(0, heap.last):
  58. stdout.write($heap.heap[i].data, "\n")
  59. var heap: PBinHeap[int]
  60. newBinHeap(heap, 256)
  61. add(heap, 1, 100)
  62. print(heap)
  63. block tgeneric2:
  64. type
  65. TX = Table[string, int]
  66. proc foo(models: seq[TX]): seq[int] =
  67. result = @[]
  68. for model in models.items:
  69. result.add model["foobar"]
  70. type
  71. Obj = object
  72. field: Table[string, string]
  73. var t: Obj
  74. discard initTable[type(t.field), string]()
  75. block tgeneric4:
  76. type
  77. TIDGen[A: Ordinal] = object
  78. next: A
  79. free: seq[A]
  80. proc newIDGen[A]: TIDGen[A] =
  81. newSeq result.free, 0
  82. var x = newIDGen[int]()