ttupleunpack.nim 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. proc returnsTuple(): (int, int, int) = (4, 2, 3)
  2. proc main2 =
  3. let (x, _, z) = returnsTuple()
  4. proc main() =
  5. proc foo(): tuple[x, y, z: int] =
  6. return (4, 2, 3)
  7. var (x, _, y) = foo()
  8. doAssert x == 4
  9. doAssert y == 3
  10. var (a, _, _) = foo()
  11. doAssert a == 4
  12. var (aa, _, _) = foo()
  13. doAssert aa == 4
  14. iterator bar(): tuple[x, y, z: int] =
  15. yield (1,2,3)
  16. for x, y, _ in bar():
  17. doAssert x == 1
  18. doAssert y == 2
  19. main()
  20. main2()
  21. block: # nested unpacking
  22. block: # simple let
  23. let (a, (b, c), d) = (1, (2, 3), 4)
  24. doAssert (a, b, c, d) == (1, 2, 3, 4)
  25. let foo = (a, (b, c), d)
  26. let (a2, (b2, c2), d2) = foo
  27. doAssert (a, b, c, d) == (a2, b2, c2, d2)
  28. block: # var and assignment
  29. var (x, (y, z), t) = ('a', (true, @[123]), "abc")
  30. doAssert (x, y, z, t) == ('a', true, @[123], "abc")
  31. (x, (y, z), t) = ('b', (false, @[456]), "def")
  32. doAssert (x, y, z, t) == ('b', false, @[456], "def")
  33. block: # very nested
  34. let (_, (_, (_, (_, (_, a))))) = (1, (2, (3, (4, (5, 6)))))
  35. doAssert a == 6
  36. block: # const
  37. const (a, (b, c), d) = (1, (2, 3), 4)
  38. doAssert (a, b, c, d) == (1, 2, 3, 4)
  39. const foo = (a, (b, c), d)
  40. const (a2, (b2, c2), d2) = foo
  41. doAssert (a, b, c, d) == (a2, b2, c2, d2)
  42. block: # evaluation semantics preserved between literal and not literal
  43. var s: seq[string]
  44. block: # literal
  45. let (a, (b, c), d) = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
  46. doAssert (a, b, c, d) == (1, 2, 3, 4)
  47. doAssert s == @["a", "b", "c", "d"]
  48. block: # underscore
  49. s = @[]
  50. let (a, (_, c), _) = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
  51. doAssert (a, c) == (1, 3)
  52. doAssert s == @["a", "b", "c", "d"]
  53. block: # temp
  54. s = @[]
  55. let foo = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
  56. let (a, (b, c), d) = foo
  57. doAssert (a, b, c, d) == (1, 2, 3, 4)
  58. doAssert s == @["a", "b", "c", "d"]
  59. block: # unary assignment unpacking
  60. var a: int
  61. (a,) = (1,)
  62. doAssert a == 1