titer7.nim 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. discard """
  2. output: '''--- evens
  3. 2
  4. 4
  5. 6
  6. 8
  7. --- squares
  8. 1
  9. 4
  10. 9
  11. 16
  12. 25
  13. 36
  14. 49
  15. 64
  16. 81
  17. '''
  18. """
  19. iterator `/`[T](sequence: seq[T],
  20. filter: proc(e:T):bool {.closure.}) : T =
  21. for element in sequence:
  22. if (filter(element)):
  23. yield element
  24. iterator `>>`[I,O](sequence: seq[I],
  25. map: proc(e:I):O {.closure.}) : O =
  26. for element in sequence:
  27. yield map(element)
  28. iterator `/>>`[I,O](sequence: seq[I],
  29. filtermap:tuple[
  30. f:proc(e:I):bool {.closure.},
  31. m:proc(e:I):O {.closure.}]) : O =
  32. for element in sequence:
  33. if (filtermap.f(element)):
  34. yield filtermap.m(element)
  35. proc isEven(x:int): bool =
  36. (x and 1) == 0
  37. proc square(x:int): int =
  38. x * x
  39. let list = @[1,2,3,4,5,6,7,8,9]
  40. echo ("--- evens")
  41. for item in list / isEven: echo(item)
  42. echo ("--- squares")
  43. for item in list >> square: echo(item)
  44. #echo ("--- squares of evens, only")
  45. # next line doesn't compile. Generic types are not inferred
  46. #for item in list />> (isEven, square) : echo(item)