Skip to content
Snippets Groups Projects
Commit df884409 authored by Benjamin Stamm's avatar Benjamin Stamm
Browse files

corrected German stuff in worksheet 2...

parent 20c68aa6
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id:4fe99eff-729a-4d93-ab82-487e5143bae5 tags:
# Advanced Data Types
%% Cell type:markdown id:5de78ecc-bbde-49ff-b618-b8c8c440ce47 tags:
# Fortgeschrittene Datentypen
%% Cell type:markdown id:7969b8f9-335a-4bd2-82f7-1d9795234ed5 tags:
## Dictionaries
%% Cell type:markdown id:8ffb53e2-1813-4fdf-962e-e066bc9b737c tags:
## Wörterbücher
## Zuordnungstabellen (assoziative Listen)
%% Cell type:markdown id:ea8518c1-8e1d-4532-8055-e04c3aa3e7c4 tags:
A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.
The function `Dict` creates a new dictionary with no items. Because Dict is the name of a built-in function, you should avoid using it as a variable name.
The function `Dict` creates a new dictionary with no items. Because `Dict` is the name of a built-in function, you should avoid using it as a variable name.
%% Cell type:markdown id:548487ed-dc9d-4404-a2ab-451c0ea742e4 tags:
Ein Wörterbuch enthält eine Sammlung von Indizes, die als Schlüssel bezeichnet werden, und eine Sammlung von Werten. Jeder Schlüssel ist mit einem einzigen Wert verbunden. Die Zuordnung eines Schlüssels und eines Wertes wird als Schlüssel-Wert-Paar oder manchmal als Element bezeichnet.
Eine Zuordnungstabelle enthält eine Sammlung von Indizes, die als Schlüssel bezeichnet werden, und eine Sammlung von Werten. Jeder Schlüssel ist mit einem einzigen Wert verbunden. Die Zuordnung eines Schlüssels und eines Wertes wird als Schlüssel-Wert-Paar oder manchmal als Element bezeichnet.
Die Funktion `Dict` erstellt ein neues Wörterbuch ohne Elemente. Da Dict der Name einer integrierten Funktion ist, sollte man ihn vermeiden, als Variablenname zu verwenden.
Die Funktion `Dict` erstellt ein neues Wörterbuch ohne Elemente. Da `Dict` der Name einer integrierten Funktion ist, sollte man vermeiden ihn als Variablenname zu verwenden.
%% Cell type:code id:59ae8d17-a6f6-4210-95bc-0e7492bc8a7a tags:
``` julia
eng2de = Dict()
```
%% Cell type:code id:28490ea3-c4d3-4e4d-915f-612ad36c9472 tags:
``` julia
eng2de["one"] = "ein";
```
%% Cell type:markdown id:f2aff40c-6dcb-421a-b67f-1662c5bf4702 tags:
You can also initialize a dictionary with items as:
%% Cell type:markdown id:09b62b4d-748b-4e1d-91f2-7db610ad02ac tags:
Du kannst auch ein Wörterbuch mit Elementen initialisieren, wie folgt:
Du kannst auch eine Zuordnungstabelle mit Elementen wie folgt initialisieren:
%% Cell type:code id:92fc203b-4ba8-432a-a541-c4ccf3292195 tags:
``` julia
eng2de = Dict("one" => "ein", "two" => "zwei", "three" => "drei")
```
%% Cell type:markdown id:c52d24af-ec90-4b8c-bdd9-988129a7fa81 tags:
Dictionaries are mutable, meaning that it is always possible to modify their elements, add new key-value pairs or removing existing ones.
%% Cell type:markdown id:809e7c99-22f0-4440-921d-e5904cadc8a4 tags:
Wörterbücher sind veränderbar, was bedeutet, dass es immer möglich ist, ihre Elemente zu ändern, neue Schlüssel-Wert-Paare hinzuzufügen oder bestehende zu entfernen.
%% Cell type:code id:22b295dc-994e-4bbc-ac8d-da5ab9e73493 tags:
``` julia
eng2de["four"] = "VIER"
@show eng2de
eng2de["four"] = "vier"
@show eng2de
delete!(eng2de, "four")
@show eng2de;
```
%% Cell type:markdown id:01513ad2-3083-4c89-adca-ccc8a88d93d4 tags:
In general, the order of the key-value pairs is unpredictable. However this is not important, as the values are always accessed using the keys.
%% Cell type:markdown id:d8b4ee03-5592-4567-883b-e0842fefeff4 tags:
Im Allgemeinen ist die Reihenfolge der Schlüssel-Wert-Paare unvorhersehbar. Dies ist jedoch nicht wichtig, da die Werte immer mithilfe der Schlüssel abgerufen werden.
%% Cell type:code id:e9e4c5b9-9539-4294-a6ec-0a29fb76bf7b tags:
``` julia
eng2de["two"]
```
%% Cell type:markdown id:9944dbbd-478b-4ae1-ac89-e16be08a0868 tags:
If the key isn’t in the dictionary, you get an exception:
%% Cell type:markdown id:84cf8b52-f061-4b28-a327-bc527820517c tags:
Wenn der Schlüssel nicht im Wörterbuch vorhanden ist, tritt eine Ausnahme auf:
Wenn der Schlüssel nicht im Wörterbuch vorhanden ist, tritt eine Fehlermeldung auf:
%% Cell type:code id:8221269b-7a8f-4cfd-ab8e-0aa4fd6c962d tags:
``` julia
eng2de["four"]
```
%% Cell type:markdown id:a545abaa-78dc-4625-84e9-03b1c8beaaf8 tags:
The `length` function works on dictionaries; it returns the number of key-value pairs:
%% Cell type:markdown id:f83d51c5-2c1d-4449-8cd5-e80f224b9a76 tags:
Die Funktion `length` funktioniert auch bei Wörterbüchern; sie gibt die Anzahl der Schlüssel-Wert-Paare zurück:
Die Funktion `length` funktioniert auch bei Zuordnungstabellen; sie gibt die Anzahl der Schlüssel-Wert-Paare zurück:
%% Cell type:code id:0e242667-b921-4242-bdcc-cbcac14909b2 tags:
``` julia
length(eng2de)
```
%% Cell type:markdown id:8e42655b-f2a0-41f0-be90-015ebfeafdb9 tags:
The function `keys` returns a collection with the keys of the dictionary:
%% Cell type:markdown id:b4ac7b46-9fc0-47fd-b6c0-c97791517b51 tags:
Die Funktion `keys` gibt eine Sammlung mit den Schlüsseln des Wörterbuchs zurück:
%% Cell type:code id:3236f973-d3fa-42ba-a1c0-41e0002446cb tags:
``` julia
keys(eng2de)
```
%% Cell type:markdown id:acfa7044-5695-4af8-b4bc-320c8a48a220 tags:
Now you can use the `∈` operator to see whether something appears as a key in the dictionary:
%% Cell type:markdown id:f9bc6fe5-3f7a-458e-942a-11bd3e83dcc6 tags:
Nun kannst du den Operator `∈` verwenden, um zu sehen, ob etwas als Schlüssel im Wörterbuch vorhanden ist:
%% Cell type:code id:1fdeb10c-0d84-4c22-b734-d68e2eafe375 tags:
``` julia
@show "one" keys(eng2de)
@show "four" keys(eng2de);
```
%% Cell type:markdown id:986919d6-4f27-4fad-b222-20697bf6af40 tags:
To see whether something appears as a value in a dictionary, you can use the function `values`, which returns a collection of values, and then use the `∈` operator:
%% Cell type:markdown id:864d141e-6cd2-45e6-95fe-e84cca35cf70 tags:
Um zu überprüfen, ob etwas als Wert in einem Wörterbuch vorhanden ist, kannst du die Funktion `values` verwenden, die eine Sammlung von Werten zurückgibt, und dann den Operator `∈` verwenden:
%% Cell type:code id:ab90dad1-61d0-4dbd-b829-a354c13fcb71 tags:
``` julia
@show "ein" values(eng2de)
@show "vier" values(eng2de);
```
%% Cell type:markdown id:049c9dfd-1e51-4898-98e5-a4b812d0bba2 tags:
### Loops over dictionaries
You can traverse the keys of the dictionary in a `for` statement.
%% Cell type:markdown id:5b255b31-8aca-49b4-a95f-302c59baa975 tags:
### Schleifen über Wörterbücher
### Schleifen über Zuordnungstabellen
Du kannst die Schlüssel des Wörterbuchs in einer `for`-Schleife durchlaufen.
Du kannst die Schlüssel der Zuordnungstabelle in einer `for`-Schleife durchlaufen.
%% Cell type:code id:e7062d3f-2125-4ecd-ab13-d04944a71fe1 tags:
``` julia
function print_dictionary(dic)
for key in keys(dic)
println(key, " ", dic[key])
end
end
print_dictionary(eng2de)
```
%% Cell type:markdown id:cf27195c-e601-49ca-b03d-63162bf59bce tags:
Again, the keys are in no particular order. To traverse the keys in alphabetically sorted order, you can combine `sort` and `collect`:
%% Cell type:markdown id:a6b3285a-58f6-41b6-8755-2732a367424e tags:
Auch hier sind die Schlüssel in keiner bestimmten Reihenfolge. Um die Schlüssel in alphabetisch sortierter Reihenfolge zu durchlaufen, kannst du `sort` und `collect` kombinieren:
%% Cell type:code id:6d52aeba-3c7e-405c-bcfe-d76e37e94f51 tags:
``` julia
function print_dictionary_sorted(dic)
for key in sort(collect(keys(dic)))
println(key, " ", dic[key])
end
end
print_dictionary_sorted(eng2de)
```
%% Cell type:markdown id:8daa9d3e-19de-4415-ba6c-6aeb174b38fa tags:
### Exercises
### Exercise
- Write a function that given a string as input counts how many times each letter appears. Use a dictionary.
%% Cell type:markdown id:964165ee-4d0d-4122-b6b2-d3926101cab2 tags:
### Übungen
### Übung
- Schreibe eine Funktion, die bei Eingabe eines Strings zählt, wie oft jeder Buchstabe vorkommt. Verwende ein Wörterbuch.
%% Cell type:code id:aba1978b-e675-48a7-89aa-75553db70537 tags:
``` julia
```
%% Cell type:markdown id:3a9b281f-6cc0-4d39-b9e2-d816823f9873 tags:
## Tuples and named tuples
%% Cell type:markdown id:0acaa2f9-372c-4a3e-be01-27cfe2853fdb tags:
## Tupel und benannte Tupel
%% Cell type:markdown id:a722109e-86cc-44e3-9256-a3e93a1668f5 tags:
A tuple is a sequence of values. The values can be of any type, and they are indexed by integers. The tuples are immutable and each element can have its own type.
%% Cell type:markdown id:68ea4303-ce3c-4647-8e9f-89afd0a6a670 tags:
Ein Tupel ist eine Sequenz von Werten. Die Werte können beliebigen Typs sein und sie werden durch Ganzzahlen indexiert. Die Tupel sind unveränderlich und jedes Element kann seinen eigenen Typ haben.
%% Cell type:code id:8502cf2e-8bea-4707-811c-f4e6e1de3c8f tags:
``` julia
t = 'a', 'b', 'c', 'd', 'e'
```
%% Cell type:markdown id:d01f5647-a240-4620-9a3a-782835aca39c tags:
Although it is not necessary, it is common to enclose tuples in parentheses:
%% Cell type:markdown id:2632b11b-de4b-4f21-bcc6-06a32517c121 tags:
Obwohl es nicht notwendig ist, ist es üblich, Tupel in Klammern zu setzen:
%% Cell type:code id:bfa31b99-bf9d-49bb-babc-fe8a65248429 tags:
``` julia
t = ('a', 'b', 'c', 'd', 'e')
```
%% Cell type:markdown id:3fa935e0-0611-4b8a-982c-329c33a74f99 tags:
To create a tuple with a single element, you have to include a final comma:
%% Cell type:markdown id:86fa8b6b-bbbf-4c9c-a5c0-63b00b2c59cb tags:
Um ein Tupel mit einem einzigen Element zu erstellen, musst du ein abschließendes Komma setzen:
%% Cell type:code id:cb1bea15-2b80-43b2-be8e-27507d550fca tags:
``` julia
t1 = ('a',)
@show typeof(t1)
t2 = ('a')
@show typeof(t2);
```
%% Cell type:markdown id:193457ac-4e4b-4e58-8c28-6d8b4331d532 tags:
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
%% Cell type:markdown id:d6f34b5b-2aaa-49db-b2a8-d5891fe33ee1 tags:
Eine andere Möglichkeit, ein Tupel zu erstellen, ist die integrierte Funktion `tuple`. Ohne Argument erstellt sie ein leeres Tupel:
%% Cell type:code id:952acafe-ca5d-4b58-8969-224b0fe3a28f tags:
``` julia
t3 = tuple()
@show typeof(t3)
t4 = tuple(1, 'a', π, 12.0)
@show typeof(t4);
```
%% Cell type:markdown id:729c3597-1a35-4a26-ae7a-6dadee31daeb tags:
Using the bracket operator it is possible to access an element. Note, differently from other programming languages (for example C, C++, Python) in Julia the first element is 1.
%% Cell type:markdown id:efc3d061-7e93-4863-a802-a7cdb869af7e tags:
Mit dem eckigen Klammern-Operator ist es möglich, auf ein Element zuzugreifen. Beachte, dass in Julia das erste Element, anders als in anderen Programmiersprachen (zum Beispiel C, C++, Python), mit 1 indexiert wird.
%% Cell type:code id:9817c28f-428d-4d5b-8384-608f9b4d763d tags:
``` julia
t4[2]
```
%% Cell type:markdown id:2519be57-8c10-4878-a772-017b099f6a4c tags:
It is also possible to get multiple elements by using slices.
%% Cell type:markdown id:17a0f0ee-e03f-4669-a5f1-889d875577d9 tags:
Es ist auch möglich, mehrere Elemente mithilfe von Slices zu erhalten.
%% Cell type:code id:c48ac07f-3a4e-4bb8-9551-2973ea8d2f9c tags:
``` julia
@show t4[1:3];
```
%% Cell type:markdown id:aeda8602-f9da-4173-a692-54e2e9a0e178 tags:
But if you try to modify one of the elements of the tuple, you get an error:
%% Cell type:markdown id:d0f25a1f-0a4c-4ab4-a339-f5ba64806681 tags:
Aber wenn du versuchst, eines der Elemente des Tupels zu ändern, tritt ein Fehler auf:
%% Cell type:code id:cfc94cc9-832c-45d2-85b8-aaf789f33f6a tags:
``` julia
t4[2] = 'b'
```
%% Cell type:markdown id:b9f13b5c-9e61-46b9-a47d-f90199bd7bd2 tags:
Because tuples are immutable, you can’t modify the elements.
%% Cell type:markdown id:d956168e-36e4-4abb-a3d6-3c53a857e78d tags:
Da Tupel unveränderlich sind, kannst du die Elemente nicht ändern.
%% Cell type:markdown id:a10cb9a7-8f44-44f8-831f-178b780e4ac9 tags:
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x ÷ y and then x % y. It is better to compute them both at the same time.
The built-in function `divrem` takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:
%% Cell type:markdown id:6a115819-54fd-4550-b097-59fea3ecb523 tags:
Genau genommen kann eine Funktion nur einen Wert zurückgeben, aber wenn der Wert ein Tupel ist, hat dies den gleichen Effekt wie das Zurückgeben mehrerer Werte. Zum Beispiel, wenn du zwei Ganzzahlen teilen und den Quotienten und den Rest berechnen möchtest, ist es ineffizient, zuerst x ÷ y und dann x % y zu berechnen. Es ist besser, beides gleichzeitig zu berechnen.
Die integrierte Funktion `divrem` nimmt zwei Argumente entgegen und gibt ein Tupel aus zwei Werten zurück, dem Quotienten und dem Rest. Du kannst das Ergebnis als Tupel speichern:
%% Cell type:code id:d1dde137-036f-4b93-8010-13b3e835ebd8 tags:
``` julia
t = divrem(7, 3)
```
%% Cell type:markdown id:ea615dbd-effb-4442-b160-20e7c9b6c22e tags:
Alternatively, we can use tuple assignment to store the elements separately:
%% Cell type:markdown id:9cd48d9c-cf1d-4546-a2c0-4bb54a42e1e8 tags:
Alternativ können wir die Zuweisung als Tupel verwenden, um die Elemente getrennt zu speichern:
%% Cell type:code id:c4969556-7945-43c9-8b96-1ea1032cbb3c tags:
``` julia
q, r = divrem(7, 3)
@show q r;
```
%% Cell type:markdown id:4574e191-aaa8-4834-8837-54947d6ddf30 tags:
### Gather and scatter
Functions can take a variable number of arguments. A parameter name that ends with `...` gathers arguments into a tuple. For example, `printall` takes any number of arguments and prints them one by line:
%% Cell type:markdown id:e4177fab-a386-4274-8657-bbc6698ec1e5 tags:
### Sammeln und verteilen
Funktionen können eine variable Anzahl von Argumenten entgegennehmen. Ein Parametername, der mit `...` endet, sammelt die Argumente in ein Tupel. Zum Beispiel nimmt `printall` eine beliebige Anzahl von Argumenten entgegen und gibt sie nacheinander aus:
%% Cell type:code id:43f8c7ad-5ac2-425e-a50f-c45624bb3d8a tags:
``` julia
function printall(args...)
for arg in args
println(arg)
end
end
printall(1)
printall(1, 2.0, '3')
```
%% Cell type:markdown id:eb662374-fe83-49d7-a5be-d9582d037ad1 tags:
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the `...` operator. For example, `divrem` takes exactly two arguments; it doesn’t work with a tuple:
%% Cell type:markdown id:28b3cd91-bf05-43bc-a253-2bee077a1df1 tags:
Das Gegenstück zu "sammeln" ist "verteilen". Wenn du eine Sequenz von Werten hast und sie als mehrere Argumente an eine Funktion übergeben möchtest, kannst du den Operator `...` verwenden. Zum Beispiel nimmt `divrem` genau zwei Argumente an; es funktioniert nicht mit einem Tupel:
%% Cell type:code id:bf55fc10-8432-41e3-bd6c-2244c8c96513 tags:
``` julia
t = (7, 3)
divrem(t)
```
%% Cell type:markdown id:d05def39-3244-4acd-a082-a7ee532f8f1d tags:
But if you scatter the tuple, it works:
%% Cell type:markdown id:db3cd00d-d41c-4f68-95d4-c4e5b283734a tags:
Aber wenn du das Tupel verteilst, funktioniert es:
Wenn du aber das Tupel verteilst, funktioniert es:
%% Cell type:code id:e7df53bc-6b2d-4501-9ca8-61e3cb79eb1a tags:
``` julia
t = (7, 3)
divrem(t...)
```
%% Cell type:markdown id:2cf01c32-9d1b-4e83-9375-f737e51c58ed tags:
### Dictionaries and Tuples
%% Cell type:markdown id:dad5d7bf-0dd5-450b-90f3-7768f2d91c18 tags:
### Wörterbücher und Tupel
### Zuordnungstabellen und Tupel
%% Cell type:markdown id:00e97ccc-8e64-4eef-84be-85a266eb3490 tags:
Dictionaries can be used as iterators that iterate the key-value pairs. You can use it in a `for` loop like this:
%% Cell type:markdown id:3a38cabd-b056-4140-a75c-e0fa383a2a74 tags:
Wörterbücher können als Iteratoren verwendet werden, um die Schlüssel-Wert-Paare zu durchlaufen. Du kannst es in einer `for`-Schleife wie folgt verwenden:
Zuordnungstabellen können als Iteratoren verwendet werden, um die Schlüssel-Wert-Paare zu durchlaufen. Du kannst es in einer `for`-Schleife wie folgt verwenden:
%% Cell type:code id:ed483334-36d0-4700-b178-cd9dc5f12189 tags:
``` julia
d = Dict('a'=>1, 'b'=>2, 'c'=>3);
for (key, value) in d
println(key, " ", value)
end
```
%% Cell type:markdown id:dcb05236-810a-410b-aaa0-0cb431e3e64f tags:
It is common to use tuples as keys in dictionaries. For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:
%% Cell type:markdown id:5a012731-cf42-487b-9d02-4a4b1d0475c0 tags:
Es ist üblich, Tupel als Schlüssel in Wörterbüchern zu verwenden. Zum Beispiel könnte ein Telefonverzeichnis Nachname-Vorname-Paare auf Telefonnummern abbilden. Angenommen, wir haben last, first und number definiert, könnten wir schreiben:
Es ist üblich, Tupel als Schlüssel in Zuordnungstabellen zu verwenden. Zum Beispiel könnte ein Telefonverzeichnis Nachname-Vorname-Paare auf Telefonnummern abbilden. Angenommen, wir haben last, first und number definiert, könnten wir schreiben:
%% Cell type:markdown id:e5462d35-fa68-42d8-ba00-c5dd1747c557 tags:
`directory[last, first] = number`
%% Cell type:markdown id:9980d710-392b-4716-b44d-98e6c5c8b838 tags:
### Named tuples
%% Cell type:markdown id:7bd0a942-de38-4c9e-96df-a786fa814254 tags:
### Benannte Tupel
%% Cell type:markdown id:e514c4bd-c17c-44f4-a89f-88154cc1bf6c tags:
Named tuples are a special type of tuple in Julia where each element has a specific name associated with it. This allows you to access elements by their names, making the code more readable and self-explanatory.
%% Cell type:markdown id:2284786f-cb8b-4173-944a-e50d79ceca2d tags:
Benannte Tupel sind ein besonderer Tupeltyp in Julia, bei dem jedem Element ein spezifischer Name zugeordnet ist. Dies ermöglicht es dir, auf Elemente anhand ihrer Namen zuzugreifen, was den Code lesbarer und selbsterklärender macht.
%% Cell type:code id:78fb5959-407a-4128-9287-bb9d455f22dc tags:
``` julia
person = (name = "Michele", age = 28, city = "Stuttgart")
```
%% Cell type:markdown id:63075b2d-ef86-48e4-8f84-981f81fdece0 tags:
Named tuples are immutable, however it is possible to update the content, or to add new elements, by creating a new version. For example:
%% Cell type:markdown id:01e99a5c-f331-4ad6-95e0-e403b8ad327b tags:
Benannte Tupel sind unveränderlich, aber es ist möglich, den Inhalt zu aktualisieren oder neue Elemente hinzuzufügen, indem eine neue Version erstellt wird. Zum Beispiel:
%% Cell type:code id:ecd22e07-5ba3-4f11-bc77-d967a6fc3fe8 tags:
``` julia
updated_person = (person..., age = 29)
updated_person = (person..., number = "0711 ...")
```
%% Cell type:markdown id:347fe4ea-5b63-4fb8-91bc-2b7b8a0c6a30 tags:
### Exercises
### Exercise
- Write a function `swap_first_last` that takes a tuple and returns a new tuple with the first and last elements swapped. Tip: use a combination of the `...` operator and of this slice `[2:end-1]`.
%% Cell type:markdown id:70061322-9435-496a-ac0d-c026f41e5936 tags:
### Exercises
- Write a function `swap_first_last` that takes a tuple and returns a new tuple with the first and last elements swapped. Tip: use a combination of the `...` operator and of this slice `[2:end-1]`.
### Übung
- Schreibe eine Funktion `swap_first_last`, die ein Tupel entgegennimmt und ein neues Tupel zurückgibt, bei dem das erste und das letzte Element vertauscht sind. Tipp: Verwende eine Kombination des `...`-Operators und des Slices `[2:end-1]`.
%% Cell type:code id:3721b654-b182-426d-b799-a69e0b53a550 tags:
``` julia
```
%% Cell type:markdown id:647530cd-480a-414f-a8ec-1375e05a9e1b tags:
## Objects and structs
%% Cell type:markdown id:5629a477-5d19-43a2-8bb4-e10b10f2ffde tags:
## Objekte und Strukturen
%% Cell type:markdown id:00b9bdb1-86ad-47f6-b8c3-88e85878eaff tags:
At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn how to build your own types to organize both code and data.
We have used many of Julia’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space.
There are several ways we might represent points in Julia:
- We could store the coordinates separately in two variables, x and y.
- We could store the coordinates as elements in an tuple.
- We could create a new type to represent points as objects.
Here we will investigate the third option.
%% Cell type:markdown id:18412e4f-e5fb-4a92-a083-ac2e5b58cde3 tags:
Zu diesem Zeitpunkt weißt du bereits, wie man Funktionen verwendet, um Code zu organisieren, und integrierte Typen, um Daten zu organisieren. Der nächste Schritt ist zu lernen, wie man eigene Typen erstellt, um sowohl Code als auch Daten zu organisieren.
Wir haben viele der integrierten Typen von Julia verwendet; jetzt werden wir einen neuen Typ definieren. Als Beispiel werden wir einen Typ namens Punkt erstellen, der einen Punkt im zweidimensionalen Raum repräsentiert.
Es gibt verschiedene Möglichkeiten, wie wir Punkte in Julia darstellen könnten:
- Wir könnten die Koordinaten separat in zwei Variablen, x und y, speichern.
- Wir könnten die Koordinaten als Elemente in einem Tupel speichern.
- Wir könnten einen neuen Typ erstellen, um Punkte als Objekte darzustellen.
Hier werden wir die dritte Option untersuchen.
%% Cell type:markdown id:9aa53d46-033b-4559-a5d8-e95357a257a5 tags:
A programmer-defined composite type is also called a struct. The struct definition for a point looks like this:
%% Cell type:markdown id:270c430a-4157-4e54-bb27-660c4028e5c6 tags:
Ein vom Programmierer definierter zusammengesetzter Typ wird auch als Struktur (engl. struct) bezeichnet. Die Strukturdefinition für einen Punkt sieht so aus:
%% Cell type:code id:c2e3f646-2d82-46a4-a265-01b919412c6d tags:
``` julia
struct Point
x::Real
y::Real
end
```
%% Cell type:markdown id:fb9be134-9730-4dbd-9e05-51dd94e9d8e0 tags:
The header indicates that the new struct is called Point. The body defines the attributes or fields of the struct. The Point struct has two fields: x and y.
A struct is like a factory for creating objects. To create a point, you call Point as if it were a function having as arguments the values of the fields. When Point is used as a function, it is called a constructor. The constructor returns an instance of the object.
%% Cell type:markdown id:6b99219f-70ba-41a7-8c52-e3803a360087 tags:
Die Kopfzeile zeigt an, dass die neue Struktur Point genannt wird. Der Körper definiert die Attribute oder Felder der Struktur. Die Point-Struktur hat zwei Felder: x und y.
Eine Struktur ist wie eine Fabrik zur Erzeugung von Objekten. Um einen Punkt zu erstellen, rufst du Point auf, als wäre es eine Funktion, und übergibst die Werte der Felder als Argumente. Wenn Point als Funktion verwendet wird, wird dies Konstruktor genannt. Der Konstruktor gibt eine Instanz des Objekts zurück.
%% Cell type:code id:197339a2-0d8b-4882-bab2-80ba56410f21 tags:
``` julia
p = Point(3.0, 4.0)
@show p;
```
%% Cell type:markdown id:b0134aa7-f356-4d71-9d46-959bd3cfe89a tags:
The type speficication (`::Real`) is optional, but can be helpful to enforce correct usage of the struct.
%% Cell type:markdown id:e35cbbf5-491e-44ff-b2c0-0cf6a8853083 tags:
Die Typangabe (`::Real`) ist optional, kann aber hilfreich sein, um die korrekte Verwendung der Struktur zu erzwingen.
%% Cell type:code id:849f1460-d228-4b22-a797-1077d75d1a2d tags:
``` julia
p = Point("a", 4.0)
```
%% Cell type:markdown id:e3011b23-816d-4aa2-be61-7eb8f4aee9d1 tags:
The values of the fields can be accessed using the `.` operator.
%% Cell type:markdown id:b86615f4-592f-41f7-b9d1-f5d1573cfd86 tags:
Die Werte der Felder können mithilfe des `.` Operators abgerufen werden.
%% Cell type:code id:00d090e4-d74d-4fad-ae8b-369c1046e48b tags:
``` julia
@show p.x p.y;
@show distance = sqrt(p.x^2 + p.y^2);
```
%% Cell type:markdown id:08748a8c-f76c-4f14-b3d2-9db99fb28e87 tags:
Structs are however by default immutable, after construction the fields can not change value:
%% Cell type:markdown id:7c6baa9c-56e2-4595-9e6b-c798d9cea002 tags:
Die Werte der Felder können mithilfe des `.` Operators abgerufen werden.
%% Cell type:code id:91bd6248-a358-43e3-90cc-6b8398445aaf tags:
``` julia
p.x = 2
```
%% Cell type:markdown id:629c1004-5d0f-4093-b546-473c94c91b44 tags:
Where required, mutable composite types can be declared with the keyword mutable struct. Here is the definition of a mutable point:
%% Cell type:markdown id:48b46edb-b8fd-46ca-a2ec-4aa0acbf6c01 tags:
Wenn erforderlich, können veränderbare zusammengesetzte Typen mit dem Schlüsselwort `mutable struct` deklariert werden. Hier ist die Definition eines veränderbaren Punkts:
%% Cell type:code id:804c2c32-7a84-4261-88d8-1bad6ba5e18c tags:
``` julia
mutable struct MPoint
x::Real
y::Real
end
p = MPoint(3.0, 4.0)
p.x = 2.0
@show p;
```
%% Cell type:markdown id:1bd558dd-e6c3-4dc0-9476-768c59178708 tags:
A third option is to let some fields of an unmutable struct to be mutable. For example a dictionary inside an unmutable struct can be modified.
%% Cell type:markdown id:06f44f63-bf8e-45f5-9495-006e21fc7560 tags:
Eine dritte Option ist es, einige Felder einer unveränderlichen Struktur als veränderbar zu definieren. Zum Beispiel kann ein Wörterbuch innerhalb einer unveränderlichen Struktur geändert werden.
Eine dritte Option ist es, einige Felder einer unveränderlichen Struktur als veränderbar zu definieren. Zum Beispiel kann eine Zuordnungstabellen innerhalb einer unveränderlichen Struktur geändert werden.
%% Cell type:code id:62cab9ae-5e58-401c-bc93-17720914e530 tags:
``` julia
struct Book
title::String
author::String
properties::Dict{String, Any}
end
book = Book("Der Hobbit", "J.R.R. Tolkien", Dict("available" => false))
@show book
book.properties["available"] = true
@show book;
```
%% Cell type:markdown id:31e2098b-5079-4cb5-bf64-a7a78754af32 tags:
You can pass an instance as an argument in the usual way. For example:
%% Cell type:markdown id:53aa5851-35c2-4dd0-a1e0-b5bc8e21b9f6 tags:
Du kannst eine Instanz auf die übliche Weise als Argument übergeben. Zum Beispiel:
%% Cell type:code id:e6113221-0c03-484a-99e0-f7d4fab70f03 tags:
``` julia
function print_point(p)
println("($(p.x), $(p.y))")
end
print_point(p)
```
%% Cell type:code id:d5c6fa9e-c31d-4aff-a3fd-db3449904519 tags:
``` julia
function print_book(book)
println("Title: $(book.title)")
println("Author: $(book.author)")
available = book.properties["available"]
println("Available: $(available)")
end
print_book(book)
```
%% Cell type:markdown id:3b12a004-81d9-4bbc-9e2e-d2c281dcbe18 tags:
Functions can return instances as return values.
%% Cell type:markdown id:916562a2-3402-41bb-b15d-01333915df99 tags:
Funktionen können Instanzen als Rückgabewerte zurückgeben.
%% Cell type:code id:9c57c9f7-c4fd-4263-a55f-62f123aaaa8a tags:
``` julia
function find_center(point1, point2)
x = (point1.x + point2.x)/2.0
y = (point1.y + point2.y)/2.0
return Point(x, y)
end
point1 = Point(0.0, 0.0)
point2 = Point(10.0, 10.0)
@show find_center(point1, point2);
```
%% Cell type:markdown id:078b31ab-11e1-4596-8271-f0d33418eab8 tags:
### Exercise
- Write a function called `point_distance` which takes two points as arguments and returns the Euclidean distance between them.
%% Cell type:markdown id:4afa9ca0-e6cd-4713-8caa-689c9dfdee42 tags:
### Übung
- Schreibe eine Funktion namens `point_distance`, die zwei Punkte als Argumente entgegennimmt und die euklidische Distanz zwischen ihnen zurückgibt.
%% Cell type:code id:b5957a05-e396-41c3-9b8f-f14f089115ab tags:
``` julia
```
%% Cell type:markdown id:0fb1f6bc-e6e5-4897-bbb6-880e40e3bf20 tags:
### References and values
Each object (instance of a struct) is stored at some memory address. The operator `===` checks if two variables point to the same memory address of the object. For example
%% Cell type:markdown id:eecb6161-768e-4ae6-a600-d892894f8824 tags:
### Referenzen und Werte
Jedes Objekt (Instanz einer Struktur) wird an einer bestimmten Speicheradresse gespeichert. Der Operator `===` überprüft, ob zwei Variablen auf die gleiche Speicheradresse des Objekts zeigen. Zum Beispiel
%% Cell type:code id:ed713d91-17f4-4010-a7d3-d39826cffc97 tags:
``` julia
book_copy = book
@show book_copy === book;
```
%% Cell type:markdown id:636b6713-f4ed-4220-a159-2918bd44f78e tags:
This means that any change made to `book_copy` will also modify `book`.
%% Cell type:markdown id:582e0ac0-2304-429e-a678-c37ab157d5d6 tags:
Das bedeutet, dass jede Änderung, die an `book_copy` vorgenommen wird, auch `book` modifiziert.
%% Cell type:code id:a9c46bac-d234-4616-a604-63bdf03b1393 tags:
``` julia
book.properties["available"] = true
book_copy.properties["available"] = false
@show book;
```
%% Cell type:markdown id:6bcbf983-40fa-4fc8-8eca-7cd7c45778dc tags:
If a new, distinct, object is needed (in other words, a copy by value), we can use the function `deepcopy`.
%% Cell type:markdown id:79339467-8994-4a5c-8987-3420d14cb290 tags:
If a new, distinct, object is needed (in other words, a copy by value), we can use the function `deepcopy`.
Wenn ein neues, eindeutiges Objekt benötigt wird (mit anderen Worten, eine Kopie nach Wert), können wir die Funktion `deepcopy` verwenden.
%% Cell type:code id:c36d23c8-2292-4568-aef4-7416c6f3e538 tags:
``` julia
book_copy = deepcopy(book)
@show book_copy === book;
```
%% Cell type:markdown id:02cc3ec7-e712-4c4b-abf5-9bfc98e68a91 tags:
Finally, the `==` operator between structs defaults to the `===` operator as Julia has no way of knowing how to compare custom structs. However, it is always possible to reimplement the `==` operator for our custom types.
%% Cell type:markdown id:4cc4c096-d856-4d43-8808-94edcd3ad906 tags:
Schließlich entspricht der `==` Operator zwischen Strukturen standardmäßig dem `===` Operator, da Julia nicht weiß, wie benutzerdefinierte Strukturen verglichen werden sollen. Es ist jedoch immer möglich, den `==` Operator für unsere benutzerdefinierten Typen neu zu implementieren.
%% Cell type:code id:3372eb89-cde6-4040-aa51-b4e76af97851 tags:
``` julia
import Base: ==
function ==(book1::Book, book2::Book)
return book1.title == book2.title && book1.author == book2.author
end
@show book_copy == book;
@show book_copy === book;
```
%% Cell type:markdown id:87c1e4fb-d4e2-4ada-a97f-61273012146c tags:
With this we can compare if two books are the same, even if they are two distinct instances of the same struct.
%% Cell type:markdown id:02b533ba-2325-488a-838b-94cdf5ca25bb tags:
Damit können wir vergleichen, ob zwei Bücher gleich sind, auch wenn es sich um zwei unterschiedliche Instanzen desselben Typs handelt.
%% Cell type:markdown id:9263a1ae-52ee-4afc-9d9f-0f1341b64bc0 tags:
## Pure and impure functions
%% Cell type:markdown id:4e457ee2-813a-42a8-8ee0-600bb4b50812 tags:
## Reine und unreine Funktionen
%% Cell type:markdown id:f638e9b3-9926-46fc-81e0-d49c877a3bbb tags:
We have seen that it is quite convenient to pass objects to functions. So far we have seen functions that print the content or that create a new object. None of these functions are modifying the content of the input objects.
- A function that does not modify the input it is also said **pure**.
- A function which modifies the input it is said **impure**. In Julia impure functions are highlighted by adding a `!` as the last character of the name.
Let's consider a modified version of the book for an example.
%% Cell type:markdown id:fb008ae0-a457-45db-8f77-425d56e95b30 tags:
Wir haben gesehen, dass es ziemlich praktisch ist, Objekte an Funktionen zu übergeben. Bisher haben wir Funktionen gesehen, die den Inhalt ausgeben oder ein neues Objekt erstellen. Keine dieser Funktionen ändert den Inhalt der Eingabeobjekte.
- Eine Funktion, die die Eingabe nicht ändert, wird auch als **rein** bezeichnet.
- Eine Funktion, die die Eingabe ändert, wird als **unrein** bezeichnet. In Julia werden unreine Funktionen durch Hinzufügen eines `!` als letztem Zeichen des Namens hervorgehoben.
Betrachten wir eine modifizierte Version des Buchs als Beispiel.
%% Cell type:code id:7f892e07-a601-4cba-b58d-40be9c8e93ab tags:
``` julia
book = Book("Der Hobbit", "J.R.R. Tolkien", Dict("available" => true, "copies_in_stock" => 10))
@show book;
```
%% Cell type:markdown id:99f4d6c9-2633-4394-b6a0-e0ce0c05e0db tags:
Then we could think of a function which updates the database whenever we order new copies.
%% Cell type:markdown id:7dac83b5-1086-4ca9-9b36-827497825be6 tags:
Dann könnten wir über eine Funktion nachdenken, die die Datenbank aktualisiert, wenn wir neue Exemplare bestellen.
%% Cell type:code id:04937488-a556-44ad-97be-98b017f293fd tags:
``` julia
function order_book!(book, number_of_copies)
if number_of_copies <= 0
return
end
book.properties["copies_in_stock"] += number_of_copies
book.properties["available"] = true
end
order_book!(book, 5)
@show book;
```
%% Cell type:markdown id:b30bd560-5ff3-4706-9f53-e6a5158651e9 tags:
### Exercise
- Write an inpure function `sell_book!` for updating the book object whenever we sell a single copy. The function should complain if there are no copies available.
%% Cell type:markdown id:93bc2e46-8530-4d1e-b7fa-55a74d1831c8 tags:
### Übung
- Schreibe eine unreine Funktion `sell_book!`, um das Buchobjekt zu aktualisieren, wenn wir ein Exemplar verkaufen. Die Funktion sollte eine Meldung ausgeben, wenn keine Exemplare verfügbar sind.
%% Cell type:code id:6e79fe95-767d-4b3e-af58-623db6dc0712 tags:
``` julia
```
%% Cell type:markdown id:5ed4d4e0-0454-4298-9a56-8fb32634aa24 tags:
## Further exercises
%% Cell type:markdown id:d5bb0b58-e85e-4edb-80b6-19d2c7d49ac3 tags:
## Weitere Übungen
%% Cell type:markdown id:8446f1db-d40f-4311-9597-3b3b4d913151 tags:
- Create a time struct which stores the time of the day (hour, minute and second). Write a function which takes as input the time object and prints it. Then write a function which sums together two time objects and returns a new time object. If the total is more than 24 hours, it should reset as if it was the next day.
%% Cell type:markdown id:15fd6da2-f862-40ef-a58d-5e7be488565f tags:
- Erstelle eine Zeitstruktur, die die Uhrzeit des Tages (Stunde, Minute und Sekunde) speichert. Schreibe eine Funktion, die als Eingabe das Zeitobjekt nimmt und es ausgibt. Schreibe dann eine Funktion, die zwei Zeitobjekte zusammenzählt und ein neues Zeitobjekt zurückgibt. Wenn die Summe mehr als 24 Stunden beträgt, sollte sie wie am nächsten Tag zurückgesetzt werden.
%% Cell type:code id:5335e035-62ee-4d0f-acfc-a9e24ac26d99 tags:
``` julia
```
%% Cell type:markdown id:32844b6f-518a-4174-83c6-0d7ebeabe4e4 tags:
- Create a custom version of the `==` function which checks if two time objects are the same.
%% Cell type:markdown id:2e0fde12-1214-4709-a7cb-5ebfaa0af17a tags:
- Erstelle eine benutzerdefinierte Version der `==` Funktion, die überprüft, ob zwei Zeitobjekte identisch sind.
%% Cell type:code id:966d4db1-c95a-4531-8209-a869519599ea tags:
``` julia
```
%% Cell type:markdown id:baa7e06f-e183-4ee7-912a-e22255e18e21 tags:
- Create a custom version of the `<` and `<=` functions for time objects.
%% Cell type:markdown id:4e8c3c1e-14fb-439f-97c7-076196f7e5b4 tags:
- Erstelle eine benutzerdefinierte Version der `<` und `<=` Funktionen für Zeitobjekte.
%% Cell type:code id:c9b76667-731b-4ec2-aaf4-e94496f65b1a tags:
``` julia
```
%% Cell type:markdown id:1bdbd748-7482-4f54-99a7-3d6e74b65575 tags:
- Create a custom version of the `>` and `>=` functions for time objects.
%% Cell type:markdown id:b79aad8c-647e-46d0-9b04-6a77cd219953 tags:
- Erstelle eine benutzerdefinierte Version der `>` und `>=` Funktionen für Zeitobjekte.
%% Cell type:code id:7df56050-686e-4a87-aa86-9b7f61315aa2 tags:
``` julia
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment