tmoditer.nim 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. discard """
  2. output: "XXXXX01234"
  3. """
  4. iterator modPairs(a: var array[0..4,string]): tuple[key: int, val: var string] =
  5. for i in 0..a.high:
  6. yield (key: i, val: a[i])
  7. iterator modItems*[T](a: var array[0..4,T]): var T =
  8. for i in 0..a.high:
  9. yield a[i]
  10. var
  11. arr = ["a", "b", "c", "d", "e"]
  12. for a in modItems(arr):
  13. a = "X"
  14. for a in items(arr):
  15. stdout.write(a)
  16. for i, a in modPairs(arr):
  17. a = $i
  18. for a in items(arr):
  19. stdout.write(a)
  20. echo ""
  21. #--------------------------------------------------------------------
  22. # Lent iterators
  23. #--------------------------------------------------------------------
  24. type
  25. NonCopyable = object
  26. x: int
  27. proc `=destroy`(o: var NonCopyable) =
  28. discard
  29. proc `=copy`(dst: var NonCopyable, src: NonCopyable) {.error.}
  30. proc `=sink`(dst: var NonCopyable, src: NonCopyable) =
  31. dst.x = src.x
  32. iterator lentItems[T](a: openArray[T]): lent T =
  33. for i in 0..a.high:
  34. yield a[i]
  35. iterator lentPairs[T](a: array[0..1, T]): tuple[key: int, val: lent T] =
  36. for i in 0..a.high:
  37. yield (key: i, val: a[i])
  38. let arr1 = [1, 2, 3]
  39. let arr2 = @["a", "b", "c"]
  40. let arr3 = [NonCopyable(x: 1), NonCopyable(x: 2)]
  41. let arr4 = @[(1, "a"), (2, "b"), (3, "c")]
  42. var accum: string
  43. for x in lentItems(arr1):
  44. accum &= $x
  45. doAssert(accum == "123")
  46. accum = ""
  47. for x in lentItems(arr2):
  48. accum &= $x
  49. doAssert(accum == "abc")
  50. accum = ""
  51. for val in lentItems(arr3):
  52. accum &= $val.x
  53. doAssert(accum == "12")
  54. accum = ""
  55. for i, val in lentPairs(arr3):
  56. accum &= $i & "-" & $val.x & " "
  57. doAssert(accum == "0-1 1-2 ")
  58. accum = ""
  59. for i, val in lentItems(arr4):
  60. accum &= $i & "-" & $val & " "
  61. doAssert(accum == "1-a 2-b 3-c ")
  62. accum = ""
  63. for (i, val) in lentItems(arr4):
  64. accum &= $i & "-" & $val & " "
  65. doAssert(accum == "1-a 2-b 3-c ")