titer8.nim 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. discard """
  2. output: '''tada
  3. 1
  4. 2
  5. 3
  6. ta da1 1
  7. 1 2
  8. 1 3
  9. 2 1
  10. 2 2
  11. 2 3
  12. 3 1
  13. 3 2
  14. 3 3
  15. 0
  16. 1
  17. 2
  18. a1: A
  19. a2: A
  20. a1: B
  21. a2: B
  22. a1: C
  23. a2: C
  24. a1: D'''
  25. """
  26. # Test first class iterator:
  27. import strutils
  28. iterator tokenize2(s: string, seps: set[char] = Whitespace): tuple[
  29. token: string, isSep: bool] {.closure.} =
  30. var i = 0
  31. while i < s.len:
  32. var j = i
  33. if s[j] in seps:
  34. while j < s.len and s[j] in seps: inc(j)
  35. if j > i:
  36. yield (substr(s, i, j-1), true)
  37. else:
  38. while j < s.len and s[j] notin seps: inc(j)
  39. if j > i:
  40. yield (substr(s, i, j-1), false)
  41. i = j
  42. iterator count3(): int {.closure.} =
  43. yield 1
  44. yield 2
  45. yield 3
  46. for word, isSep in tokenize2("ta da", WhiteSpace):
  47. if not isSep:
  48. stdout.write(word)
  49. echo ""
  50. proc inProc() =
  51. for c in count3():
  52. echo c
  53. for word, isSep in tokenize2("ta da", WhiteSpace):
  54. stdout.write(word)
  55. for c in count3():
  56. for d in count3():
  57. echo c, " ", d
  58. inProc()
  59. iterator count0(): int {.closure.} =
  60. # note: doesn't require anything in its closure (except 'state')
  61. yield 0
  62. iterator count2(): int {.closure.} =
  63. # note: requires 'x' in its closure
  64. var x = 1
  65. yield x
  66. inc x
  67. yield x
  68. # a first class iterator has the type 'proc {.closure.}', but maybe
  69. # it shouldn't:
  70. proc invoke(iter: iterator(): int {.closure.}) =
  71. for x in iter(): echo x
  72. invoke(count0)
  73. invoke(count2)
  74. # simple tasking:
  75. type
  76. TTask = iterator (ticker: int)
  77. iterator a1(ticker: int) {.closure.} =
  78. echo "a1: A"
  79. yield
  80. echo "a1: B"
  81. yield
  82. echo "a1: C"
  83. yield
  84. echo "a1: D"
  85. iterator a2(ticker: int) {.closure.} =
  86. echo "a2: A"
  87. yield
  88. echo "a2: B"
  89. yield
  90. echo "a2: C"
  91. proc runTasks(t: varargs[TTask]) =
  92. var ticker = 0
  93. while true:
  94. let x = t[ticker mod t.len]
  95. if finished(x): break
  96. x(ticker)
  97. inc ticker
  98. runTasks(a1, a2)