From d0176f97304733e3b673e76d386f6db5458bf9d7 Mon Sep 17 00:00:00 2001 From: Lambert Theisen <lambert.theisen@rwth-aachen.de> Date: Thu, 26 Oct 2023 16:58:24 +0200 Subject: [PATCH] Translate sheet 3 (except the last Exercise) --- src/3_Data_Types_Multiple_Dispatch.ipynb | 546 +++++++++++++++++++++-- 1 file changed, 498 insertions(+), 48 deletions(-) diff --git a/src/3_Data_Types_Multiple_Dispatch.ipynb b/src/3_Data_Types_Multiple_Dispatch.ipynb index eaad59d..5da094d 100644 --- a/src/3_Data_Types_Multiple_Dispatch.ipynb +++ b/src/3_Data_Types_Multiple_Dispatch.ipynb @@ -15,6 +15,22 @@ "These concepts enhance Julia's performance, especially in mathematical and scientific computing.\n" ] }, + { + "cell_type": "markdown", + "id": "3ba487cb", + "metadata": {}, + "source": [ + "# Datentypen und Multiple Dispatch\n", + "\n", + "In diesem Notizbuch werden wir die grundlegenden Konzepte von Julias Typsystem erforschen und Multiple Dispatch verstehen, wobei wir uns konzentrieren auf:\n", + "\n", + "- Abstrakte und Konkrete Typen\n", + "- Dynamische Typen\n", + "- Multiple Dispatch\n", + "\n", + "Diese Konzepte verbessern Julias Leistung, insbesondere bei mathematischer und wissenschaftlicher Datenverarbeitung." + ] + }, { "cell_type": "markdown", "id": "7128c447", @@ -23,6 +39,14 @@ "## Abstract and concrete types" ] }, + { + "cell_type": "markdown", + "id": "fe56dbef", + "metadata": {}, + "source": [ + "## Abstrakte and konkrete Typen" + ] + }, { "cell_type": "markdown", "id": "723212c2", @@ -35,6 +59,18 @@ "- **Concrete Types**: Can be instantiated and are used to create objects." ] }, + { + "cell_type": "markdown", + "id": "01604e4c", + "metadata": {}, + "source": [ + "Bevor wir den Multiple Dispatch von Funktionen und den Dispatch nach Typen besprechen, werfen wir kurz einen Blick auf Julias Typsystem. \n", + "Typen in Julia fallen in zwei Kategorien: **Abstrakt** und **konkret**.\n", + "\n", + "- **Abstrakte Typen**: Können nicht instanziiert werden und dienen dazu, allgemeine Kategorien von Objekten darzustellen.\n", + "- **Konkrete Typen**: Können instanziiert werden und werden verwendet, um Objekte zu erstellen.\n" + ] + }, { "cell_type": "markdown", "id": "58c7dc0c", @@ -50,6 +86,21 @@ "- `supertype(T)`: Get the direct supertype of type T." ] }, + { + "cell_type": "markdown", + "id": "41e57dbd", + "metadata": {}, + "source": [ + "In Julia gibt es mehrere eingebaute Funktionen, die sich auf das Abfragen und Arbeiten mit Typen beziehen.\n", + "Hier eine Auswahl einiger wichtiger:\n", + "\n", + "- `<:`: Der Subtyp-Operator, der verwendet wird, um zu überprüfen, ob ein Typ ein Subtyp eines anderen Typs ist.\n", + "- `isabstracttype(T)`: Überprüfen, ob T ein abstrakter Typ ist.\n", + "- `isconcretetype(T)`: Überprüfen, ob T ein konkreter Typ ist.\n", + "- `subtypes(T)`: Eine Liste aller unmittelbaren Subtypen des Typs T erhalten.\n", + "- `supertype(T)`: Den direkten Supertyp des Typs T erhalten.\n" + ] + }, { "cell_type": "markdown", "id": "00533545", @@ -58,6 +109,14 @@ "Abstract types such as `Integer` or `Number` are supertypes of a bunch of other types, for example:" ] }, + { + "cell_type": "markdown", + "id": "da96b9b9", + "metadata": {}, + "source": [ + "Abstrakte Typen wie `Integer` oder `Number` sind Supertypen von vielen anderen Typen, zum Beispiel:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -69,7 +128,7 @@ "@show UInt16 <: Integer # UInt16 is a sub-type of Integer\n", "@show Float32 <: Integer # Float32 is not a sub-type of Integer\n", "@show Float32 <: Number # Float32 is a sub-type of Number\n", - "@show Integer <: Number; # Integer is a sub-type of Nummber" + "@show Integer <: Number; # Integer is a sub-type of Nummber\n" ] }, { @@ -82,7 +141,7 @@ "# by transitivity:\n", "@show Int32 <: Number\n", "@show UInt16 <: Number\n", - "@show Number <: Number;" + "@show Number <: Number;\n" ] }, { @@ -94,6 +153,15 @@ "We can check type properties in various ways:" ] }, + { + "cell_type": "markdown", + "id": "027b76c8", + "metadata": {}, + "source": [ + "### Eigenschaften von Typen\n", + "Wir können Typ-Eigenschaften auf verschiedene Weisen überprüfen:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -101,7 +169,7 @@ "metadata": {}, "outputs": [], "source": [ - "@show isconcretetype(Int32);" + "@show isconcretetype(Int32);\n" ] }, { @@ -111,7 +179,7 @@ "metadata": {}, "outputs": [], "source": [ - "@show isabstracttype(Integer);" + "@show isabstracttype(Integer);\n" ] }, { @@ -122,6 +190,14 @@ "A fancy way is even to display a type tree:" ] }, + { + "cell_type": "markdown", + "id": "2a316d56", + "metadata": {}, + "source": [ + "Eine ausgefallene Möglichkeit ist sogar, einen Typ-Baum anzuzeigen:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -146,23 +222,23 @@ "print_type_tree(Number, max_level=7)\n", "```\n", "\"\"\"\n", - "function print_type_tree(T, level=0, max_level=typemax(Int), prefix=\"\", subtype_prefix=\"\") \n", + "function print_type_tree(T, level=0, max_level=typemax(Int), prefix=\"\", subtype_prefix=\"\")\n", " # Stop recursion if max level is reached\n", " if level >= max_level\n", " return\n", " end\n", - " \n", + "\n", " # Print current type\n", " println(prefix, subtype_prefix, T)\n", - " \n", + "\n", " # Obtain subtypes\n", " subs = subtypes(T)\n", - " \n", + "\n", " # Recursively print subtypes with adjusted prefix\n", " for (i, subtype) in enumerate(subs)\n", - " new_prefix = \" \" \n", + " new_prefix = \" \"\n", " subtype_prefix = i < length(subs) ? \"├── \" : \"└── \"\n", - " \n", + "\n", " # If the subtype has no further subtypes, avoid using the \"|\" in the prefix\n", " if isempty(subtypes(subtype))\n", " print_type_tree(subtype, level+1, max_level, prefix * \" \", subtype_prefix)\n", @@ -170,7 +246,7 @@ " print_type_tree(subtype, level+1, max_level, prefix * new_prefix, subtype_prefix)\n", " end\n", " end\n", - "end" + "end\n" ] }, { @@ -180,7 +256,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_type_tree(Number)" + "print_type_tree(Number)\n" ] }, { @@ -191,6 +267,14 @@ "**Exercise**: Write code to determine all subtypes of `Number`, whether they are abstract or concrete." ] }, + { + "cell_type": "markdown", + "id": "bc4662dc", + "metadata": {}, + "source": [ + "**Übung**: Schreiben Sie Code, um alle Subtypen von `Number` zu bestimmen, unabhängig davon, ob sie abstrakt oder konkret sind.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -198,7 +282,7 @@ "metadata": {}, "outputs": [], "source": [ - "# TODO: implement your code" + "# TODO: implement your code\n" ] }, { @@ -209,6 +293,14 @@ "To get the super type of a type, one can use `supertype`:" ] }, + { + "cell_type": "markdown", + "id": "3ad36e86", + "metadata": {}, + "source": [ + "Um den Supertyp eines Typs zu erhalten, kann man `supertype` verwenden:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -220,7 +312,7 @@ "@show supertype(Signed)\n", "@show supertype(Float16)\n", "@show supertype(Float32)\n", - "@show supertype(Bool);" + "@show supertype(Bool);\n" ] }, { @@ -237,7 +329,7 @@ " T = supertype(T)\n", " end\n", " println(T) # Print Any, which is the ultimate supertype of all types\n", - "end" + "end\n" ] }, { @@ -247,7 +339,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_supertypes(Int64);" + "print_supertypes(Int64);\n" ] }, { @@ -257,7 +349,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_supertypes(Float64);" + "print_supertypes(Float64);\n" ] }, { @@ -268,6 +360,14 @@ "### Custom Abstract And Concrete Types" ] }, + { + "cell_type": "markdown", + "id": "d16d0857", + "metadata": {}, + "source": [ + "### Benutzerdefinierte Abstrakte und Konkrete Typen\n" + ] + }, { "cell_type": "markdown", "id": "8cbad09b", @@ -276,6 +376,14 @@ "One can define custom abstract type by using `abstract type`:" ] }, + { + "cell_type": "markdown", + "id": "882efff3", + "metadata": {}, + "source": [ + "Man kann benutzerdefinierte abstrakte Typen mit `abstract type` definieren:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -283,7 +391,7 @@ "metadata": {}, "outputs": [], "source": [ - "abstract type Animal end # Abstract type" + "abstract type Animal end # Abstract type\n" ] }, { @@ -294,6 +402,14 @@ "Then, some concrete types can be created as well:" ] }, + { + "cell_type": "markdown", + "id": "d63c0261", + "metadata": {}, + "source": [ + "Dann können auch einige konkrete Typen erstellt werden:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -321,6 +437,15 @@ "One can use subtypes to obtain all subtypes of either an abstract type or a concrete type." ] }, + { + "cell_type": "markdown", + "id": "091a7905", + "metadata": {}, + "source": [ + "In diesem Beispiel erstellen wir zwei konkrete Tiere, `Dog` und `Cat`.\n", + "Man kann `subtypes` verwenden, um alle Subtypen eines abstrakten oder konkreten Typs zu erhalten.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -328,7 +453,7 @@ "metadata": {}, "outputs": [], "source": [ - "subtypes(Animal)" + "subtypes(Animal)\n" ] }, { @@ -339,6 +464,14 @@ "Again, using `isabstracttype` and `isconcretetype` we have" ] }, + { + "cell_type": "markdown", + "id": "a2f3177d", + "metadata": {}, + "source": [ + "Wiederum können wir mit `isabstracttype` und `isconcretetype` überprüfen:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -352,7 +485,7 @@ "\n", "@show isconcretetype(Animal)\n", "@show isconcretetype(Dog)\n", - "@show isconcretetype(Cat);" + "@show isconcretetype(Cat);\n" ] }, { @@ -363,6 +496,14 @@ "The type tree of `Animal` is:" ] }, + { + "cell_type": "markdown", + "id": "4b08f9f7", + "metadata": {}, + "source": [ + "Der Typ-Baum von `Animal` ist:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -370,7 +511,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_type_tree(Animal)" + "print_type_tree(Animal)\n" ] }, { @@ -381,6 +522,14 @@ "Now, we create two instances from the concrete types:" ] }, + { + "cell_type": "markdown", + "id": "87e2a153", + "metadata": {}, + "source": [ + "Jetzt erstellen wir zwei Instanzen von den konkreten Typen:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -391,7 +540,7 @@ "a_dog = Dog(\"Buddy\", 3)\n", "a_cat = Cat(\"Kitty\", 2)\n", "\n", - "@show a_dog a_cat;" + "@show a_dog a_cat;\n" ] }, { @@ -402,6 +551,14 @@ "In Julia, the `isa` method is used to determine whether an instance is of a particular type, whether it is abstract or concrete:\n" ] }, + { + "cell_type": "markdown", + "id": "41ea3797", + "metadata": {}, + "source": [ + "In Julia wird die Methode `isa` verwendet, um zu bestimmen, ob eine Instanz von einem bestimmten Typ ist, egal ob er abstrakt oder konkret ist:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -412,7 +569,7 @@ "@show isa(a_dog, Dog)\n", "@show isa(a_dog, Animal)\n", "@show isa(a_dog, Cat)\n", - "@show isa(a_cat, Cat);" + "@show isa(a_cat, Cat);\n" ] }, { @@ -423,6 +580,14 @@ "The method `typeof` is used to obtain the type of an instance:" ] }, + { + "cell_type": "markdown", + "id": "ee934bc9", + "metadata": {}, + "source": [ + "Die Methode `typeof` wird verwendet, um den Typ einer Instanz zu erhalten:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -431,7 +596,7 @@ "outputs": [], "source": [ "@show typeof(a_dog)\n", - "@show typeof(a_cat);" + "@show typeof(a_cat);\n" ] }, { @@ -442,6 +607,14 @@ "We can also get all supertypes of `Dog` and `Cat`:" ] }, + { + "cell_type": "markdown", + "id": "8dc6aef6", + "metadata": {}, + "source": [ + "Wir können auch alle Supertypen von `Dog` und `Cat` erhalten:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -449,7 +622,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_supertypes(Dog)" + "print_supertypes(Dog)\n" ] }, { @@ -459,7 +632,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_supertypes(Cat)" + "print_supertypes(Cat)\n" ] }, { @@ -471,6 +644,15 @@ "Write code to implement some abstract and concrete subtypes of `Animal`, and use `print_type_tree` to view the type tree. For example you can implement the abstract type `Bird` and then a few kinds of birds." ] }, + { + "cell_type": "markdown", + "id": "d850444b", + "metadata": {}, + "source": [ + "### Übungen\n", + "Schreiben Sie Code, um einige abstrakte und konkrete Subtypen von `Animal` zu implementieren, und verwenden Sie `print_type_tree`, um den Typ-Baum anzusehen. Zum Beispiel können Sie den abstrakten Typ `Bird` implementieren und dann einige Arten von Vögeln.\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -478,7 +660,7 @@ "metadata": {}, "outputs": [], "source": [ - "# TODO: implement your code" + "# TODO: implement your code\n" ] }, { @@ -496,6 +678,19 @@ "```" ] }, + { + "cell_type": "markdown", + "id": "0add9f3d", + "metadata": {}, + "source": [ + "Welche der folgenden Typen sind Unterarten eines anderen? Versuchen Sie zuerst zu raten und überprüfen Sie dann mithilfe des Operators `<:`.\n", + "\n", + "```julia\n", + "Float64 AbstractFloat Integer\n", + "Number AbstractArray Complex\n", + "Real Any Nothing\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -503,7 +698,7 @@ "metadata": {}, "outputs": [], "source": [ - "# TODO: implement your code" + "# TODO: implement your code\n" ] }, { @@ -516,6 +711,16 @@ "More details see: [https://docs.julialang.org/en/v1/base/base/#Properties-of-Types](https://docs.julialang.org/en/v1/base/base/#Properties-of-Types)." ] }, + { + "cell_type": "markdown", + "id": "77bb1fe2", + "metadata": {}, + "source": [ + "In Julia sind konkrete Typen immer ein Blatt des Typbaums, d.h., sie können nicht voneinander abgeleitet werden. Für jemanden, der mit C++ oder Python vertraut ist (wie einige von uns), mag dies zunächst einschränkend erscheinen, aber es entfernt eine Menge unnötiger Komplexität aus der Typenhierarchie. Wir werden jetzt keine weiteren Informationen geben, der Grund wird am Ende dieses Notebooks klarer sein.\n", + "\n", + "Weitere Details finden Sie unter: [https://docs.julialang.org/en/v1/base/base/#Properties-of-Types](https://docs.julialang.org/en/v1/base/base/#Properties-of-Types).\n" + ] + }, { "cell_type": "markdown", "id": "20a01368-ff73-4992-afae-792962aee09f", @@ -548,6 +753,44 @@ " In this way, adding a new recipe for a specific kind of food does not require changing already written things. " ] }, + { + "cell_type": "markdown", + "id": "64fc3a0b", + "metadata": {}, + "source": [ + "## Mehrfachdispatch\n", + "\n", + "Mehrfachdispatch ist wahrscheinlich das Schlüsselmerkmal von Julia, das es im Vergleich zu vielen anderen Sprachen unterscheidet und ihm die Fähigkeit verleiht, gleichzeitig flexibel und leistungsstark zu sein.\n", + "\n", + "Um das Konzept des Mehrfachdispatchs vollständig zu verstehen, werden wir eine Analogie verwenden. Wir werden so tun, als ob eine Programmiersprache ein Werkzeug zum Schreiben eines Kochbuches ist. Ein Rezept kombiniert eine Zubereitungsmethode (zum Beispiel Backen, Braten) mit einer Zutat (zum Beispiel Kartoffeln, Karotten, Fisch).\n", + "\n", + "- Die erste Möglichkeit besteht darin, das Buch nach Zubereitungsmethoden zu organisieren: Jedes Kapitel erklärt ausführlich eine Zubereitungsmethode. Zum Beispiel haben wir **Kapitel 1: Backen**, **Kapitel 2: Braten** und so weiter. Der Nachteil dieses Ansatzes ist, dass wir immer dann, wenn wir eine neue Zutat hinzufügen, mehrere Kapitel ändern müssen. Dieser Ansatz, der sich auf die Aktion und nicht auf die Zutaten konzentriert, ist typisch für funktionale Programmiersprachen.\n", + "\n", + "- Die zweite Möglichkeit besteht darin, das Buch nach Zutaten zu organisieren: Jedes Kapitel konzentriert sich auf eine Zutat. Zum Beispiel haben wir **Kapitel 1: Kartoffeln**, **Kapitel 2: Fisch** und so weiter. Der Nachteil dieses Ansatzes ist, dass wir immer dann, wenn wir ein neues Rezept hinzufügen, erneut mehrere Kapitel ändern müssen. Dieser Ansatz konzentriert sich auf die Zutaten (Daten) und ist typisch für objektorientierte Programmierung, bei der wir etwas Ähnliches haben könnten wie:\n", + " ```julia\n", + " struct Kartoffeln\n", + " function backen()\n", + " function braten()\n", + " end\n", + " struct Fisch\n", + " function backen()\n", + " function braten()\n", + " end\n", + " ```\n", + "\n", + "- Julia verfolgt einen dritten Ansatz namens **Mehrfachdispatch**, bei dem die Aktion von den Daten entkoppelt wird. In unserem hypothetischen Kochbuch haben wir Kapitel wie **Kapitel 1: Kartoffeln backen**, **Kapitel 2: Kartoffeln braten**, **Kapitel 3: Fisch backen**, **Kapitel 4: Fisch braten** und so weiter. Jedes dieser Kapitel enthält etwas Ähnliches wie:\n", + " ```julia\n", + " function backen(kartoffeln::Kartoffeln)\n", + " function braten(kartoffeln::Kartoffeln)\n", + " function backen(fisch::Fisch)\n", + " function braten(fisch::Fisch)\n", + " ```\n", + "\n", + "Auf diese Weise erfordert das Hinzufügen eines neuen Rezepts für eine bestimmte Art von Lebensmittel keine Änderungen an bereits geschriebenen Dingen.\n", + "\n", + "Quelle: [https://docs.julialang.org/en/v1/base/base/#Properties-of-Types](https://docs.julialang.org/en/v1/base/base/#Properties-of-Types)\n" + ] + }, { "cell_type": "markdown", "id": "a0a6aecb-bd29-472c-921b-c4135a09b026", @@ -556,6 +799,14 @@ "Let us return back to the `mymult` function and see how we can use the multiple dispatch to implement new functionality:" ] }, + { + "cell_type": "markdown", + "id": "0198d051", + "metadata": {}, + "source": [ + "Kehren wir zur `mymult`-Funktion zurück und sehen, wie wir den Mehrfachdispatch verwenden können, um neue Funktionen zu implementieren:\n" + ] + }, { "cell_type": "code", "execution_count": null, @@ -563,7 +814,7 @@ "metadata": {}, "outputs": [], "source": [ - "mymult(x, y) = x * y" + "mymult(x, y) = x * y\n" ] }, { @@ -574,6 +825,14 @@ "We were able to safely use this functions with a number of type combinations, but some things do not yet work:" ] }, + { + "cell_type": "markdown", + "id": "a088c5fd", + "metadata": {}, + "source": [ + "Wir konnten diese Funktionen sicher mit einer Vielzahl von Typenkombinationen verwenden, aber einige Dinge funktionieren noch nicht:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -581,7 +840,7 @@ "metadata": {}, "outputs": [], "source": [ - "mymult(2, \" abc\")" + "mymult(2, \" abc\")\n" ] }, { @@ -592,6 +851,14 @@ "Let's say we wanted to concatenate the string `str` $n$ times on multiplication with an integer $n$. In Julia this functionality is already implemented by the exponentiation operator:" ] }, + { + "cell_type": "markdown", + "id": "1eda2f65", + "metadata": {}, + "source": [ + "Angenommen, wir möchten den String `str` $n$-mal aneinanderreihen, indem wir ihn mit einer ganzen Zahl $n$ multiplizieren. In Julia ist diese Funktionalität bereits durch den Potenzoperator implementiert:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -599,7 +866,7 @@ "metadata": {}, "outputs": [], "source": [ - "\"abc\"^4" + "\"abc\"^4\n" ] }, { @@ -610,6 +877,14 @@ "But for the sake of argument, assume we wanted `mymult(\"abc\", 4)` and `mymult(4, \"abc\")` to behave the same way. We define two special methods:" ] }, + { + "cell_type": "markdown", + "id": "13b4953e", + "metadata": {}, + "source": [ + "Aber der Argumentation halber nehmen wir an, wir möchten, dass `mymult(\"abc\", 4)` und `mymult(4, \"abc\")` auf die gleiche Weise funktionieren. Wir definieren zwei spezielle Methoden:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -618,7 +893,7 @@ "outputs": [], "source": [ "mymult(str::String, n::Integer) = str^n\n", - "mymult(n::Integer, str::String) = mymult(str, n)" + "mymult(n::Integer, str::String) = mymult(str, n)\n" ] }, { @@ -630,6 +905,14 @@ "considered during dispatch if the argument `str` is of type `String` and similarly `n` is an `Integer` (or subtype). Since Julia always dispatches to the most specific method in case multiple methods match, this is all we need to do:" ] }, + { + "cell_type": "markdown", + "id": "ed42c2c2", + "metadata": {}, + "source": [ + "In beiden Fällen bedeutet die Syntax `str::String` und `n::Integer`, dass die jeweilige Methode nur während der Zuordnung berücksichtigt wird, wenn das Argument `str` vom Typ `String` ist und `n` ein `Integer` (oder Untertyp) ist. Da Julia immer zur spezifischsten Methode dispatcht, falls mehrere Methoden übereinstimmen, ist dies alles, was wir tun müssen:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -637,7 +920,7 @@ "metadata": {}, "outputs": [], "source": [ - "mymult(2, \" abc\")" + "mymult(2, \" abc\")\n" ] }, { @@ -647,7 +930,7 @@ "metadata": {}, "outputs": [], "source": [ - "@which mymult(2, \" abc\")" + "@which mymult(2, \" abc\")\n" ] }, { @@ -657,7 +940,7 @@ "metadata": {}, "outputs": [], "source": [ - "@which mymult(\"def \", UInt16(3))" + "@which mymult(\"def \", UInt16(3))\n" ] }, { @@ -675,6 +958,26 @@ "```" ] }, + { + "cell_type": "markdown", + "id": "a4ccf591", + "metadata": {}, + "source": [ + "Beachten Sie, dass die vollständig generische Form:\n", + "\n", + "```julia\n", + "mymult(x, y) = x * y\n", + "```\n", + "\n", + "tatsächlich eine Abkürzung für:\n", + "\n", + "```julia\n", + "mymult(x::Any, y::Any) = x * y\n", + "```\n", + "\n", + "ist." + ] + }, { "cell_type": "markdown", "id": "eb674aa1-2380-4ae5-b7b2-ad7579239def", @@ -685,6 +988,16 @@ "In Julia different version of a function, which work on different kinds of arguments are called **methods**. You can see the list of methods by running this:" ] }, + { + "cell_type": "markdown", + "id": "ed16db85", + "metadata": {}, + "source": [ + "### Methoden\n", + "\n", + "In Julia werden verschiedene Versionen einer Funktion, die mit unterschiedlichen Arten von Argumenten arbeiten, als **Methoden** bezeichnet. Sie können die Liste der Methoden sehen, indem Sie dies ausführen:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -692,7 +1005,7 @@ "metadata": {}, "outputs": [], "source": [ - "methods(mymult)" + "methods(mymult)\n" ] }, { @@ -703,6 +1016,14 @@ "If you run methods on a core function like `*`, you will get quite a long list." ] }, + { + "cell_type": "markdown", + "id": "c3f6143a", + "metadata": {}, + "source": [ + "Wenn Sie `methods` auf eine Kernfunktion wie `*` ausführen, erhalten Sie eine ziemlich lange Liste." + ] + }, { "cell_type": "code", "execution_count": null, @@ -710,7 +1031,7 @@ "metadata": {}, "outputs": [], "source": [ - "methods(*)" + "methods(*)\n" ] }, { @@ -721,6 +1042,14 @@ "Using the macro `@which` can be used to discover which specific method is being run." ] }, + { + "cell_type": "markdown", + "id": "9bd61de6", + "metadata": {}, + "source": [ + "Das Makro `@which` kann verwendet werden, um herauszufinden, welche spezifische Methode gerade ausgeführt wird." + ] + }, { "cell_type": "code", "execution_count": null, @@ -729,7 +1058,7 @@ "outputs": [], "source": [ "println(@which \"Hello\"*\"World!\")\n", - "println(@which mymult(\"a\", 3))" + "println(@which mymult(\"a\", 3))\n" ] }, { @@ -740,6 +1069,14 @@ "We can also add some method for `Animal`, `Dog`, and `Cat`:" ] }, + { + "cell_type": "markdown", + "id": "8fb4d5c3", + "metadata": {}, + "source": [ + "Wir können auch einige Methoden für `Animal`, `Dog` und `Cat` hinzufügen:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -751,7 +1088,7 @@ "speak(animal::Animal) = \"Some generic animal noise\"\n", "# Use multiple dispatch to define method for specific types\n", "speak(animal::Dog) = \"Woof! I am $(animal.name), a dog.\"\n", - "speak(animal::Cat) = \"Meow! I am $(animal.name), a cat.\"" + "speak(animal::Cat) = \"Meow! I am $(animal.name), a cat.\"\n" ] }, { @@ -762,6 +1099,14 @@ "Then, let's test it." ] }, + { + "cell_type": "markdown", + "id": "c8c559e0", + "metadata": {}, + "source": [ + "Dann testen wir es." + ] + }, { "cell_type": "code", "execution_count": null, @@ -770,7 +1115,7 @@ "outputs": [], "source": [ "@show speak(a_dog)\n", - "@show speak(a_cat);" + "@show speak(a_cat);\n" ] }, { @@ -783,6 +1128,16 @@ "To show the role of abstract types in multiple dispatch, we go back to our food example. First we need to clarify the hierarchy of food types. We can use abstract types for that." ] }, + { + "cell_type": "markdown", + "id": "12b5d667", + "metadata": {}, + "source": [ + "### Abstrakte Typen und Mehrfachdispatch\n", + "\n", + "Um die Rolle abstrakter Typen im Mehrfachdispatch zu zeigen, kehren wir zu unserem Lebensmittelbeispiel zurück. Zunächst müssen wir die Hierarchie der Lebensmitteltypen klären. Dafür können wir abstrakte Typen verwenden." + ] + }, { "cell_type": "code", "execution_count": null, @@ -798,7 +1153,7 @@ "\n", "abstract type Fish <: FI will not be able to add him until monday as I don't have access to my notebookood end\n", "struct Salmon <: Fish end\n", - "struct Shrimps <: Fish end # not biologically a fish, but we can consider them so from a culinary point of view" + "struct Shrimps <: Fish end # not biologically a fish, but we can consider them so from a culinary point of view\n" ] }, { @@ -808,7 +1163,7 @@ "metadata": {}, "outputs": [], "source": [ - "print_type_tree(Food)" + "print_type_tree(Food)\n" ] }, { @@ -819,6 +1174,14 @@ "Now, we found a frying recipe which works decently for any kind of vegetable. Then we will write something like:" ] }, + { + "cell_type": "markdown", + "id": "0e8f258e", + "metadata": {}, + "source": [ + "Nun haben wir ein Bratrezept gefunden, das für jede Art von Gemüse recht gut funktioniert. Dann schreiben wir so etwas wie:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -829,7 +1192,7 @@ "function frying(vegetable::Vegetables)\n", " # make tempura\n", " # fry\n", - "end" + "end\n" ] }, { @@ -840,6 +1203,14 @@ "If we want to fry our vegetables, we will run" ] }, + { + "cell_type": "markdown", + "id": "517c0e6a", + "metadata": {}, + "source": [ + "Wenn wir unser Gemüse braten möchten, führen wir das folgendermaßen aus:" + ] + }, { "cell_type": "code", "execution_count": null, @@ -851,7 +1222,7 @@ "carrots = Carrots()\n", "\n", "println(@which frying(potatoes))\n", - "println(@which frying(carrots))" + "println(@which frying(carrots))\n" ] }, { @@ -862,6 +1233,14 @@ "But now we found an even more specific recipe that works even better for potatoes. What we will do is writing a new function which is specific for potatoes." ] }, + { + "cell_type": "markdown", + "id": "694b2921", + "metadata": {}, + "source": [ + "Aber jetzt haben wir ein noch spezifischeres Rezept gefunden, das noch besser für Kartoffeln funktioniert. Was wir tun werden, ist das Schreiben einer neuen Funktion, die spezifisch für Kartoffeln ist." + ] + }, { "cell_type": "code", "execution_count": null, @@ -871,7 +1250,7 @@ "source": [ "function frying(potatoes::Potatoes)\n", " # directly fry in oil\n", - "end" + "end\n" ] }, { @@ -881,7 +1260,7 @@ "metadata": {}, "outputs": [], "source": [ - "println(@which frying(potatoes))" + "println(@which frying(potatoes))\n" ] }, { @@ -895,6 +1274,18 @@ " - **Efficiency:** we can tune the specific methods to be super fast with our specific data type." ] }, + { + "cell_type": "markdown", + "id": "7a6463aa", + "metadata": {}, + "source": [ + "Dieses Beispiel zeigt wirklich die Stärke von Julia. Mehrfachdispatch ist aus folgenden Gründen gut:\n", + "\n", + "- **Flexibilität:** Es ist möglich, neue Dinge auf sehr schnelle Weise auszuprobieren. Wir implementieren einen neuen Datentyp und verwenden die Methoden, die bereits für abstrakte Typen vorhanden sind.\n", + "- **Anpassungsfähigkeit:** Das Implementieren benutzerdefinierter Verhaltensweisen für unsere Datentypen ist einfach. Wir müssen einfach eine benutzerdefinierte Methode hinzufügen.\n", + "- **Effizienz:** Wir können die spezifischen Methoden so abstimmen, dass sie mit unserem spezifischen Datentyp super schnell sind." + ] + }, { "cell_type": "markdown", "id": "b39955b1-eed2-4c1f-bb61-fdcc0554a7b7", @@ -904,6 +1295,15 @@ "Add some methods for `Animal`, `Dog` and `Cat` and other concrete type from the last exercise." ] }, + { + "cell_type": "markdown", + "id": "0687c04d", + "metadata": {}, + "source": [ + "### Übung\n", + "Fügen Sie einige Methoden für `Animal`, `Dog` und `Cat` sowie andere konkrete Typen aus der letzten Übung hinzu." + ] + }, { "cell_type": "code", "execution_count": null, @@ -911,7 +1311,7 @@ "metadata": {}, "outputs": [], "source": [ - "# TODO: implement your code here." + "# TODO: implement your code here.\n" ] }, { @@ -922,6 +1322,14 @@ "## Dynamical typing and type deduction" ] }, + { + "cell_type": "markdown", + "id": "4fb9457b", + "metadata": {}, + "source": [ + "## Dynamische Typisierung und Typableitung" + ] + }, { "cell_type": "markdown", "id": "85870a09", @@ -934,6 +1342,16 @@ "Julia is kind of both." ] }, + { + "cell_type": "markdown", + "id": "f27eca4d", + "metadata": {}, + "source": [ + "In der Programmiersprachen-Theorie fallen Typsysteme traditionell in zwei Kategorien. In **dynamisch typisierten** Sprachen wird der Typ eines Werts oder Ausdrucks nur zur Laufzeit abgeleitet, was in der Regel flexibleren Code ermöglicht. Beispiele hierfür sind Python oder MATLAB. Im Gegensatz dazu erfordern sogenannte **statisch typisierte** Sprachen (denken Sie an FORTRAN oder C++), dass die Typen bereits vor der Laufzeit bekannt sind, wenn das Programm kompiliert wird. Dies ermöglicht eine gründlichere Überprüfung auf Fehler (die sich in nicht übereinstimmenden Typen äußern können), und es führt normalerweise zu einer Leistungssteigerung, da mehr Informationen über die Speicherlayout des Programms zur Kompilierzeit bekannt sind. Als Ergebnis können Aspekte wie Vektorisierung, kontinuierliche Ausrichtung von Daten und Vorbelegung von Speicher leichter genutzt werden.\n", + "\n", + "Julia ist irgendwie beides." + ] + }, { "cell_type": "code", "execution_count": null, @@ -945,7 +1363,7 @@ "@show typeof(x)\n", "\n", "x = Cat(\"Kitty\", 3) # Now x is a Cat\n", - "@show typeof(x);" + "@show typeof(x);\n" ] }, { @@ -960,6 +1378,18 @@ "**Note:** this look up is the reason why it is not possible to instantiate abstract types, having variables of abstract types would make this operation unnecessary complicated. Moreover, it also reflects reality: a generic vegetable does not physically exist, we only have potatoes, carrots, eggplants and so on." ] }, + { + "cell_type": "markdown", + "id": "3e5a5e29", + "metadata": {}, + "source": [ + "Julias starke Betonung von Typen ist einer der Gründe für ihre Leistungsfähigkeit und Flexibilität.\n", + "\n", + "Wenn der Code vor der Ausführung vorkompiliert wird, hat der Compiler Informationen über den Typ aller Variablen im Programm. Er wird dann die beste mögliche Methode für jede dieser Variablen suchen. Wenn eine spezifische und hoch effiziente Methode gefunden wird, wird diese verwendet. Wenn eine spezifische Methode fehlt, wird die nächste Möglichkeit im Typbaum verwendet, die immer noch funktioniert, wenn auch nicht so effizient.\n", + "\n", + "**Hinweis:** Diese Suche ist der Grund, warum es nicht möglich ist, abstrakte Typen zu instanziieren. Die Verwendung von Variablen abstrakter Typen würde diesen Vorgang unnötig kompliziert machen. Außerdem spiegelt es auch die Realität wider: Ein generisches Gemüse existiert physisch nicht, wir haben nur Kartoffeln, Karotten, Auberginen und so weiter." + ] + }, { "cell_type": "markdown", "id": "27812692", @@ -971,6 +1401,17 @@ "- `Any` is the root of the type tree: Any type in Julia is a subtype of `Any`." ] }, + { + "cell_type": "markdown", + "id": "869f5fbc", + "metadata": {}, + "source": [ + "### Drei weitere Fakten über Julia-Typen:\n", + "- In Julia sind alle Typen gleich. Zum Beispiel gibt es keinen Unterschied zwischen `Int32` und `String`, obwohl der erste eine direkte Zuordnung zu Low-Level-Anweisungen in der CPU hat und der letztere nicht (im Gegensatz zu z.B. C++).\n", + "- Der Typ `Nothing` mit der einzigen Instanz `nothing` entspricht in Julia `void` in C++ oder `None` in Python. Er repräsentiert oft, dass eine Funktion nichts zurückgibt oder dass eine Variable nicht initialisiert wurde.\n", + "- `Any` ist die Wurzel des Typbaums: Jeder Typ in Julia ist ein Untertyp von `Any`." + ] + }, { "cell_type": "markdown", "id": "ebc902af", @@ -980,6 +1421,15 @@ "https://docs.julialang.org/en/v1/manual/types/" ] }, + { + "cell_type": "markdown", + "id": "1ca89804", + "metadata": {}, + "source": [ + "##### Für weitere Details\n", + "https://docs.julialang.org/en/v1/manual/types/" + ] + }, { "cell_type": "markdown", "id": "3e8c5b51-3ef6-4d40-9803-dcc2ab6eda3f", -- GitLab