tcompiletimesideeffects.nim 745 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. discard """
  2. output:
  3. '''
  4. @[0, 1, 2]
  5. @[3, 4, 5]
  6. @[0, 1, 2]
  7. 3
  8. 4
  9. '''
  10. """
  11. template runNTimes(n: int, f : untyped) : untyped =
  12. var accum: seq[type(f)]
  13. for i in 0..n-1:
  14. accum.add(f)
  15. accum
  16. var state {.compileTime.} : int = 0
  17. proc fill(): int {.compileTime.} =
  18. result = state
  19. inc state
  20. # invoke fill() at compile time as a compile time expression
  21. const C1 = runNTimes(3, fill())
  22. echo C1
  23. # invoke fill() at compile time as a set of compile time statements
  24. const C2 =
  25. block:
  26. runNTimes(3, fill())
  27. echo C2
  28. # invoke fill() at compile time after a compile time reset of state
  29. const C3 =
  30. block:
  31. state = 0
  32. runNTimes(3, fill())
  33. echo C3
  34. # evaluate fill() at compile time and use the results at runtime
  35. echo fill()
  36. echo fill()