Oktatás
* Programozás 1 + feladatsor + GitHub oldal
* Szkriptnyelvek + feladatsor + quick link
Teaching
* Programming 1 (BI) ◇ exercises ◇ quick link
teaching assets
Félévek
* 2024/25/2 * archívum
Linkek
* kalendárium - munkaszüneti napok '20 * tételsorok * jegyzetek * szakdolgozat / PhD * ösztöndíjak * certificates * C lang. * C++ * C# * Clojure * D lang. * Java * Nim * Scala
[ edit | logout ] [ sandbox | passwd ]
|
(1) tuples
|
def main():
t = (2, 4)
print(t) # (2, 4)
|
import std.stdio;
import std.typecons; // tuple()
void main()
{
Tuple!(int, int) p1 = tuple(2, 4);
writeln(p1); // Tuple!(int, int)(2, 4)
auto p2 = tuple(2, 4);
p2[0] = 1; // !!! mutable !!!
writeln(p2); // Tuple!(int, int)(1, 4)
immutable p3 = tuple(2, 4);
// p3[0] = 1; // Error
writeln(p3); // immutable(Tuple!(int, int))(2, 4)
// auto p4 = (2, 4); // Error
}
|
Notes:
- The
tuple() function returns a tuple data structure.
- It's a good idea to use automatic type inference in this case.
- Think of a tuple as a record/struct in C.
- By default, a tuple is mutable.
- If you want a Python-like, immutable tuple, then use the keyword
immutable on it.
Adding an alias
To make it more readable, consider adding an alias to your tuple.
(2) adding an alias v1
|
import std.stdio;
import std.typecons; // tuple()
alias Point = Tuple!(int, int);
void main()
{
Point p1 = tuple(2, 4);
writeln(p1); // Tuple!(int, int)(2, 4)
}
|
You can also add immutable to your alias definition:
(3) adding an alias v2
|
import std.stdio;
import std.typecons; // tuple()
alias Point = immutable Tuple!(int, int); // !!! immutable !!!
void main()
{
Point p1 = tuple(2, 4); // it's an immutable point now
// p1[0] = 1; // Error
writeln(p1); // immutable(Tuple!(int, int))(2, 4)
}
|
Using structs (poor man's NamedTuple)
Python has a NamedTuple data structure. It's a tuple, where the fields have names, similarly to a record. But it's a tuple, thus it's immutable.
In D, we have structs (see here), and we have the immutable keyword. So, we can have something similar to a NamedTuple :
(4) immutable struct
|
import std.stdio;
struct Point
{
int x;
int y;
}
void main()
{
immutable Point a = Point(1, 2);
immutable Point b = {6, 5}; // C-style
// a.x = 9; // error
writefln("A(%s, %s)", a.x, a.y); // A(1, 2)
writefln("B(%s, %s)", b.x, b.y); // B(6, 5)
writeln(a); // immutable(Point)(1, 2)
}
|
|
Blogjaim, hobbi projektjeim
* The Ubuntu Incident * Python Adventures * @GitHub * heroku * extra * haladó Python * YouTube listák
Debrecen | la France
[ edit ]
|