More about tuples
This commit is contained in:
parent
6b75246207
commit
6080b27c16
|
@ -185,13 +185,27 @@ A [very detailed comparison](https://scripter.co/notes/string-functions-nim-vs-p
|
||||||
|
|
||||||
### Python tuples
|
### Python tuples
|
||||||
|
|
||||||
Nim Tuples are close to Python namedtuples, see [manual](http://nim-lang.org/docs/manual.html#types-tuples-and-object-types).
|
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.
|
||||||
Use Nim arrays:
|
|
||||||
|
```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
|
``` Nim
|
||||||
var a = ["hi", "there"]
|
var a = ["hi", "there"]
|
||||||
var b = [1, 2, 3]
|
var b = [1, 2, 3]
|
||||||
echo b[1]
|
echo b[1] # 2
|
||||||
var c = ["hi", 1] # no mixed types please
|
var c = ["hi", 1] # Error: type mismatch (no mixed types allowed in arrays)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Python lists
|
### Python lists
|
||||||
|
|
Loading…
Reference in New Issue