tgeniteratorinblock.nim 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. discard """
  2. output: '''30
  3. 60
  4. 90
  5. 150
  6. 180
  7. 210
  8. 240
  9. 60
  10. 180
  11. 240
  12. [60, 180, 240]
  13. [60, 180]'''
  14. """
  15. import std/enumerate
  16. template map[T; Y](i: iterable[T], fn: proc(x: T): Y): untyped =
  17. iterator internal(): Y {.gensym.} =
  18. for it in i:
  19. yield fn(it)
  20. internal()
  21. template filter[T](i: iterable[T], fn: proc(x: T): bool): untyped =
  22. iterator internal(): T {.gensym.} =
  23. for it in i:
  24. if fn(it):
  25. yield it
  26. internal()
  27. template group[T](i: iterable[T], amount: static int): untyped =
  28. iterator internal(): array[amount, T] {.gensym.} =
  29. var val: array[amount, T]
  30. for ind, it in enumerate i:
  31. val[ind mod amount] = it
  32. if ind mod amount == amount - 1:
  33. yield val
  34. internal()
  35. var a = [10, 20, 30, 50, 60, 70, 80]
  36. proc mapFn(x: int): int = x * 3
  37. proc filterFn(x: int): bool = x mod 20 == 0
  38. for x in a.items.map(mapFn):
  39. echo x
  40. for y in a.items.map(mapFn).filter(filterFn):
  41. echo y
  42. for y in a.items.map(mapFn).filter(filterFn).group(3):
  43. echo y
  44. for y in a.items.map(mapFn).filter(filterFn).group(2):
  45. echo y