tconexpr.nim 808 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. discard """
  2. nimout: '''
  3. Fibonacci sequence: 0, 1, 1, 2, 3
  4. Sequence continues: 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
  5. '''
  6. """
  7. import strformat
  8. var fib_n {.compileTime.}: int
  9. var fib_prev {.compileTime.}: int
  10. var fib_prev_prev {.compileTime.}: int
  11. proc next_fib(): int {.compileTime.} =
  12. let fib = if fib_n < 2:
  13. fib_n
  14. else:
  15. fib_prev_prev + fib_prev
  16. inc(fib_n)
  17. fib_prev_prev = fib_prev
  18. fib_prev = fib
  19. fib
  20. const f0 = next_fib()
  21. const f1 = next_fib()
  22. const f2 = next_fib()
  23. const f3 = next_fib()
  24. const f4 = next_fib()
  25. static:
  26. echo fmt"Fibonacci sequence: {f0}, {f1}, {f2}, {f3}, {f4}"
  27. const fib_continues = block:
  28. var result = fmt"Sequence continues: "
  29. for i in 0..10:
  30. if i > 0:
  31. add(result, ", ")
  32. add(result, $next_fib())
  33. result
  34. static:
  35. echo fib_continues