From 6080b27c16d69a0281bb02348caa250c81c5a6b2 Mon Sep 17 00:00:00 2001 From: "chr v1.x" Date: Tue, 16 Jul 2019 18:19:33 -0700 Subject: [PATCH] More about tuples --- Nim-for-Python-Programmers.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/Nim-for-Python-Programmers.md b/Nim-for-Python-Programmers.md index 8828be7..ba44be1 100644 --- a/Nim-for-Python-Programmers.md +++ b/Nim-for-Python-Programmers.md @@ -185,13 +185,27 @@ A [very detailed comparison](https://scripter.co/notes/string-functions-nim-vs-p ### Python tuples -Nim Tuples are close to Python namedtuples, see [manual](http://nim-lang.org/docs/manual.html#types-tuples-and-object-types). -Use Nim arrays: +Nim Tuples are a lot like Python namedtuples in that the tuple members must have names in the type specification. However, they can be constructed and destructured without naming the fields. Also, you can have anonymous tuple types. See [manual](http://nim-lang.org/docs/manual.html#types-tuples-and-object-types) for a more in depth look at tuples. + +```Nim +var a = ("hi", "there") +echo a[0] # hi + +proc swap(tup: tuple[a: int, b: float]): tuple[c: float, d: int] = + (tup.b, tup.a) + +echo swap((1, 3.14) # (c: 3.14, d:1) + +let c, d = swap(8, 4.2) +``` + +In some cases where you might have used a tuple in Python, Nim Arrays can be used if you don't care what the fields are named. However, unlike tuples, arrays can only have one element type: + ``` Nim var a = ["hi", "there"] var b = [1, 2, 3] -echo b[1] -var c = ["hi", 1] # no mixed types please +echo b[1] # 2 +var c = ["hi", 1] # Error: type mismatch (no mixed types allowed in arrays) ``` ### Python lists