titer12.nim 1.6 KB

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