More about tuples

This commit is contained in:
chr v1.x 2019-07-16 18:19:33 -07:00
parent 6b75246207
commit 6080b27c16
1 changed files with 18 additions and 4 deletions

View File

@ -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