titer12.nim 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. discard """
  2. output: '''
  3. Selecting 2
  4. 1.0
  5. Selecting 4
  6. 2.0
  7. '''
  8. """
  9. # bug #5522
  10. import macros, sugar, sequtils
  11. proc tryS(f: () -> void): void =
  12. (try: f() except: discard)
  13. template trySTImpl(body: untyped): untyped =
  14. tryS do() -> auto:
  15. `body`
  16. macro tryST*(body: untyped): untyped =
  17. var b = if body.kind == nnkDo: body[^1] else: body
  18. result = quote do:
  19. trySTImpl((block:
  20. `b`
  21. ))
  22. iterator testIt(): int {.closure.} =
  23. for x in 0..10:
  24. yield x
  25. var xs = newSeq[int]()
  26. proc test = tryST do:
  27. for x in testIt():
  28. xs.add(x)
  29. test()
  30. doAssert xs == toSeq(0..10)
  31. # bug #5690
  32. proc filter[T](it: (iterator : T), f: proc(x: T): bool): (iterator : T) =
  33. return iterator (): T {.closure.} =
  34. for x in it():
  35. if f(x):
  36. yield x
  37. proc len[T](it : iterator : T) : Natural =
  38. for i in it():
  39. result += 1
  40. proc simpleSeqIterator(s :seq[int]) : iterator : int =
  41. iterator it: int {.closure.} =
  42. for x in s:
  43. yield x
  44. result = it
  45. let a = newSeq[int](99)
  46. doAssert len(simpleSeqIterator(a).filter(proc(x : int) : bool = true)) == 99
  47. # bug #5340
  48. proc where[A](input: seq[A], filter: (A) -> bool): iterator (): A =
  49. result = iterator (): A {.closure.} =
  50. for item in input:
  51. if filter(item):
  52. yield item
  53. proc select[A,B](input: iterator(): A {.closure.}, selector: (A) -> B): iterator (): B {.closure.} =
  54. result = iterator (): B =
  55. for item in input():
  56. echo "Selecting " & $item
  57. yield selector(item)
  58. let query = @[1,2,3,4].where(x=>x mod 2==0).select((x)=>x/2)
  59. for i in query():
  60. echo $i