"This exercise is about writing a custom data type for polynomials, a set of constructors for them, and functions to perform operations on them. **Note:** writing custom polynomials in this way is neither efficient nor convenient, but it is a great example of the topics seen so far.\n",
"\n",
" - Implement a new abstract type `AbstractPolynomial`. Then, implement a few concrete subtypes, `PolynomialDegree0`, `PolynomialDegree1`, `PolynomialDegree2` and `PolynomialArbitraryDegree`. **Tip:** use a dictionary to store the coefficients and do it in a consistent way between the various subtypes: you can use the power of `x` as the key for the coefficient value.\n",
"\n",
" - Write a constructor for each of them which takes as input the coefficients. **Tip:** use `args::Real...` to gather an arbitrary number of arguments, specifying the type is important for avoiding ambiguity when calling with one argument (try not specyifing `Real` to see the problem).\n",
"\n",
" - Write a function `Polynomial` with multiple methods: depending on the number of arguments, it should call the correct constructor. **Tips:** you can use the shorthand `Polynomial(c0) = PolynomialDegree0(c0)` to write more concise code, and you should again use `args...` to support an arbitrary amount of arguments.\n",
"\n",
" - Implement a method of the `+` function which sums together two `AbstractPolynomial`. It should work with any combination of the concrete types. It should also use a loop over the coefficients. **Note:** implementing a method for a function of the core library requires first to import it `import Base.:+`.\n",
"\n",
" - Implement some more methods of the `+` library which sum together polynomials of low degree, they should not use a for loop.\n",
"\n",
" - Last, benchmark the `+` function for two `PolynomialDegree1` polynomials and for two `PolynomialArbitraryDegree` of degree 1. **Tips:** generate random coefficients using `rand()`, repeat the process a few thousands times to get a measurable run time, use the macro `@time` to get the time."
]
]
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "bd273bc8-96ea-4260-93db-4934b7291965",
"id": "3e8c5b51-3ef6-4d40-9803-dcc2ab6eda3f",
"metadata": {},
"metadata": {},
"source": [
"source": [
"Implement a new abstract type `Polynomial` which is a subtype of `Number`.\n",
"## Übung\n",
"\n",
"Diese Übung befasst sich mit dem Schreiben eines benutzerdefinierten Datentyps für Polynome, einer Reihe von Konstruktoren dafür und Funktionen zum Durchführen von Operationen an ihnen. **Hinweis:** Das Schreiben benutzerdefinierter Polynome auf diese Weise ist weder effizient noch bequem, aber es ist ein gutes Beispiel für die bisher behandelten Themen.\n",
"\n",
"- Implementieren Sie einen neuen abstrakten Datentyp `AbstractPolynomial`. Dann implementieren Sie einige konkrete Untertypen, `PolynomialDegree0`, `PolynomialDegree1`, `PolynomialDegree2` und `PolynomialArbitraryDegree`. **Tipp:** Verwenden Sie ein Wörterbuch, um die Koeffizienten auf konsistente Weise zwischen den verschiedenen Untertypen zu speichern: Sie können die Potenz von `x` als Schlüssel für den Koeffizientenwert verwenden.\n",
"\n",
"- Schreiben Sie einen Konstruktor für jeden von ihnen, der die Koeffizienten als Eingabe erhält. **Tipp:** Verwenden Sie `args::Real...`, um eine beliebige Anzahl von Argumenten zu sammeln. Die Angabe des Typs ist wichtig, um Unklarheiten beim Aufruf mit einem Argument zu vermeiden (versuchen Sie, `Real` nicht anzugeben, um das Problem zu sehen).\n",
"\n",
"- Schreiben Sie eine Funktion `Polynomial` mit mehreren Methoden: Abhängig von der Anzahl der Argumente sollte sie den richtigen Konstruktor aufrufen. **Tipps:** Sie können die Kurzform `Polynomial(c0) = PolynomialDegree0(c0)` verwenden, um den Code kürzer zu schreiben, und Sie sollten erneut `args...` verwenden, um eine beliebige Anzahl von Argumenten zu unterstützen.\n",
"\n",
"\n",
"TO BE FINISHED"
"- Implementieren Sie eine Methode der `+` Funktion, die zwei `AbstractPolynomial` zusammenzählt. Es sollte mit jeder Kombination der konkreten Typen funktionieren. Es sollte auch eine Schleife über die Koeffizienten verwenden. **Hinweis:** Das Implementieren einer Methode für eine Funktion der Kernbibliothek erfordert zunächst das Importieren von `import Base.:+`.\n",
"\n",
"- Implementieren Sie einige weitere Methoden der `+`-Bibliothek, die Polynome niedriger Ordnung zusammenzählen. Diese sollten keine Schleife verwenden.\n",
"\n",
"- Zuletzt führen Sie eine Leistungsbewertung der `+` Funktion für zwei `PolynomialDegree1`-Polynome und für zwei `PolynomialArbitraryDegree`-Polynome vom Grad 1 durch. **Tipps:** Generieren Sie zufällige Koeffizienten mit `rand()`, wiederholen Sie den Vorgang einige Tausend Mal, um eine messbare Laufzeit zu erhalten, verwenden Sie die Makro `@time`, um die Zeit zu messen.\n"
In this notebook, we will explore the fundamental concepts of Julia's type system and understand multiple dispatch, focusing on:
In this notebook, we will explore the fundamental concepts of Julia's type system and understand multiple dispatch, focusing on:
- Abstract and Concrete Types
- Abstract and Concrete Types
- Dynamic Types
- Dynamic Types
- Multiple Dispatch
- Multiple Dispatch
These concepts enhance Julia's performance, especially in mathematical and scientific computing.
These concepts enhance Julia's performance, especially in mathematical and scientific computing.
%% Cell type:markdown id:3ba487cb tags:
%% Cell type:markdown id:3ba487cb tags:
# Datentypen und Multiple Dispatch
# Datentypen und Multiple Dispatch
In diesem Notizbuch werden wir die grundlegenden Konzepte von Julias Typsystem erforschen und Multiple Dispatch verstehen, wobei wir uns konzentrieren auf:
In diesem Notizbuch werden wir die grundlegenden Konzepte von Julias Typsystem erforschen und Multiple Dispatch verstehen, wobei wir uns konzentrieren auf:
- Abstrakte und Konkrete Typen
- Abstrakte und Konkrete Typen
- Dynamische Typen
- Dynamische Typen
- Multiple Dispatch
- Multiple Dispatch
Diese Konzepte verbessern Julias Leistung, insbesondere bei mathematischer und wissenschaftlicher Datenverarbeitung.
Diese Konzepte verbessern Julias Leistung, insbesondere bei mathematischer und wissenschaftlicher Datenverarbeitung.
%% Cell type:markdown id:7128c447 tags:
%% Cell type:markdown id:7128c447 tags:
## Abstract and concrete types
## Abstract and concrete types
%% Cell type:markdown id:fe56dbef tags:
%% Cell type:markdown id:fe56dbef tags:
## Abstrakte and konkrete Typen
## Abstrakte and konkrete Typen
%% Cell type:markdown id:723212c2 tags:
%% Cell type:markdown id:723212c2 tags:
Before we discuss multiple dispatch of functions and dispatch by types, we briefly review Julia's type system.
Before we discuss multiple dispatch of functions and dispatch by types, we briefly review Julia's type system.
Types in Julia fall into two categories: **Abstract** and **concrete**.
Types in Julia fall into two categories: **Abstract** and **concrete**.
-**Abstract Types**: Cannot be instantiated and serve to represent general categories of objects.
-**Abstract Types**: Cannot be instantiated and serve to represent general categories of objects.
-**Concrete Types**: Can be instantiated and are used to create objects.
-**Concrete Types**: Can be instantiated and are used to create objects.
%% Cell type:markdown id:01604e4c tags:
%% Cell type:markdown id:01604e4c tags:
Bevor wir den Multiple Dispatch von Funktionen und den Dispatch nach Typen besprechen, werfen wir kurz einen Blick auf Julias Typsystem.
Bevor wir den Multiple Dispatch von Funktionen und den Dispatch nach Typen besprechen, werfen wir kurz einen Blick auf Julias Typsystem.
Typen in Julia fallen in zwei Kategorien: **Abstrakt** und **konkret**.
Typen in Julia fallen in zwei Kategorien: **Abstrakt** und **konkret**.
-**Abstrakte Typen**: Können nicht instanziiert werden und dienen dazu, allgemeine Kategorien von Objekten darzustellen.
-**Abstrakte Typen**: Können nicht instanziiert werden und dienen dazu, allgemeine Kategorien von Objekten darzustellen.
-**Konkrete Typen**: Können instanziiert werden und werden verwendet, um Objekte zu erstellen.
-**Konkrete Typen**: Können instanziiert werden und werden verwendet, um Objekte zu erstellen.
%% Cell type:markdown id:58c7dc0c tags:
%% Cell type:markdown id:58c7dc0c tags:
In Julia, there are several built-in functions related to querying and working with types.
In Julia, there are several built-in functions related to querying and working with types.
Here is a selection of some important ones:
Here is a selection of some important ones:
-`<:`: The subtype operator used to check if a type is a subtype of another type.
-`<:`: The subtype operator used to check if a type is a subtype of another type.
-`isabstracttype(T)`: Check if T is an abstract type.
-`isabstracttype(T)`: Check if T is an abstract type.
-`isconcretetype(T)`: Check if T is a concrete type.
-`isconcretetype(T)`: Check if T is a concrete type.
-`subtypes(T)`: Get a list of all immediate subtypes of type T.
-`subtypes(T)`: Get a list of all immediate subtypes of type T.
-`supertype(T)`: Get the direct supertype of type T.
-`supertype(T)`: Get the direct supertype of type T.
%% Cell type:markdown id:41e57dbd tags:
%% Cell type:markdown id:41e57dbd tags:
In Julia gibt es mehrere eingebaute Funktionen, die sich auf das Abfragen und Arbeiten mit Typen beziehen.
In Julia gibt es mehrere eingebaute Funktionen, die sich auf das Abfragen und Arbeiten mit Typen beziehen.
Hier eine Auswahl einiger wichtiger:
Hier eine Auswahl einiger wichtiger:
-`<:`: Der Subtyp-Operator, der verwendet wird, um zu überprüfen, ob ein Typ ein Subtyp eines anderen Typs ist.
-`<:`: Der Subtyp-Operator, der verwendet wird, um zu überprüfen, ob ein Typ ein Subtyp eines anderen Typs ist.
-`isabstracttype(T)`: Überprüfen, ob T ein abstrakter Typ ist.
-`isabstracttype(T)`: Überprüfen, ob T ein abstrakter Typ ist.
-`isconcretetype(T)`: Überprüfen, ob T ein konkreter Typ ist.
-`isconcretetype(T)`: Überprüfen, ob T ein konkreter Typ ist.
-`subtypes(T)`: Eine Liste aller unmittelbaren Subtypen des Typs T erhalten.
-`subtypes(T)`: Eine Liste aller unmittelbaren Subtypen des Typs T erhalten.
-`supertype(T)`: Den direkten Supertyp des Typs T erhalten.
-`supertype(T)`: Den direkten Supertyp des Typs T erhalten.
%% Cell type:markdown id:00533545 tags:
%% Cell type:markdown id:00533545 tags:
Abstract types such as `Integer` or `Number` are supertypes of a bunch of other types, for example:
Abstract types such as `Integer` or `Number` are supertypes of a bunch of other types, for example:
%% Cell type:markdown id:da96b9b9 tags:
%% Cell type:markdown id:da96b9b9 tags:
Abstrakte Typen wie `Integer` oder `Number` sind Supertypen von vielen anderen Typen, zum Beispiel:
Abstrakte Typen wie `Integer` oder `Number` sind Supertypen von vielen anderen Typen, zum Beispiel:
%% Cell type:code id:50b00765 tags:
%% Cell type:code id:50b00765 tags:
``` julia
``` julia
@showInt32<:Integer# Read Int32 is a sub-type of Integer
@showInt32<:Integer# Read Int32 is a sub-type of Integer
@showUInt16<:Integer# UInt16 is a sub-type of Integer
@showUInt16<:Integer# UInt16 is a sub-type of Integer
@showFloat32<:Integer# Float32 is not a sub-type of Integer
@showFloat32<:Integer# Float32 is not a sub-type of Integer
@showFloat32<:Number# Float32 is a sub-type of Number
@showFloat32<:Number# Float32 is a sub-type of Number
@showInteger<:Number;# Integer is a sub-type of Nummber
@showInteger<:Number;# Integer is a sub-type of Nummber
```
```
%% Cell type:code id:329380e7 tags:
%% Cell type:code id:329380e7 tags:
``` julia
``` julia
# by transitivity:
# by transitivity:
@showInt32<:Number
@showInt32<:Number
@showUInt16<:Number
@showUInt16<:Number
@showNumber<:Number;
@showNumber<:Number;
```
```
%% Cell type:markdown id:aa54bfef tags:
%% Cell type:markdown id:aa54bfef tags:
### Type properties
### Type properties
We can check type properties in various ways:
We can check type properties in various ways:
%% Cell type:markdown id:027b76c8 tags:
%% Cell type:markdown id:027b76c8 tags:
### Eigenschaften von Typen
### Eigenschaften von Typen
Wir können Typ-Eigenschaften auf verschiedene Weisen überprüfen:
Wir können Typ-Eigenschaften auf verschiedene Weisen überprüfen:
%% Cell type:code id:49228132 tags:
%% Cell type:code id:49228132 tags:
``` julia
``` julia
@showisconcretetype(Int32);
@showisconcretetype(Int32);
```
```
%% Cell type:code id:9ffd1775 tags:
%% Cell type:code id:9ffd1775 tags:
``` julia
``` julia
@showisabstracttype(Integer);
@showisabstracttype(Integer);
```
```
%% Cell type:markdown id:a778662d tags:
%% Cell type:markdown id:a778662d tags:
A fancy way is even to display a type tree:
A fancy way is even to display a type tree:
%% Cell type:markdown id:2a316d56 tags:
%% Cell type:markdown id:2a316d56 tags:
Eine ausgefallene Möglichkeit ist sogar, einen Typ-Baum anzuzeigen:
Eine ausgefallene Möglichkeit ist sogar, einen Typ-Baum anzuzeigen:
Print a tree structure that visualizes the type hierarchy rooted at `T`.
Print a tree structure that visualizes the type hierarchy rooted at `T`.
# Parameters
# Parameters
- `T`: The type which serves as the root of the tree to print.
- `T`: The type which serves as the root of the tree to print.
- `level`: (Optional, default=`0`) An integer specifying the current recursion depth - typically not provided by the user.
- `level`: (Optional, default=`0`) An integer specifying the current recursion depth - typically not provided by the user.
- `max_level`: (Optional, default=`typemax(Int)`) An integer specifying the maximum recursion depth, i.e., how many levels deep into the type hierarchy to print.
- `max_level`: (Optional, default=`typemax(Int)`) An integer specifying the maximum recursion depth, i.e., how many levels deep into the type hierarchy to print.
- `prefix`: (Optional, default=`""`) A string used internally to format the tree structure - typically not provided by the user.
- `prefix`: (Optional, default=`""`) A string used internally to format the tree structure - typically not provided by the user.
- `subtype_prefix`: (Optional, default=`""`) A string used internally to format the tree structure - typically not provided by the user.
- `subtype_prefix`: (Optional, default=`""`) A string used internally to format the tree structure - typically not provided by the user.
# Usage
# Usage
```julia
```julia
print_type_tree(Number, max_level=7)
print_type_tree(Number, max_level=7)
```
```
"""
"""
function print_type_tree(T, level=0, max_level=typemax(Int), prefix="", subtype_prefix="")
function print_type_tree(T, level=0, max_level=typemax(Int), prefix="", subtype_prefix="")
**Exercise**: Write code to determine all subtypes of `Number`, whether they are abstract or concrete.
**Exercise**: Write code to determine all subtypes of `Number`, whether they are abstract or concrete.
%% Cell type:markdown id:bc4662dc tags:
%% Cell type:markdown id:bc4662dc tags:
**Übung**: Schreiben Sie Code, um alle Subtypen von `Number` zu bestimmen, unabhängig davon, ob sie abstrakt oder konkret sind.
**Übung**: Schreiben Sie Code, um alle Subtypen von `Number` zu bestimmen, unabhängig davon, ob sie abstrakt oder konkret sind.
%% Cell type:code id:39b8339f tags:
%% Cell type:code id:39b8339f tags:
``` julia
``` julia
# TODO: implement your code
# TODO: implement your code
```
```
%% Cell type:markdown id:dacc835e tags:
%% Cell type:markdown id:dacc835e tags:
To get the super type of a type, one can use `supertype`:
To get the super type of a type, one can use `supertype`:
%% Cell type:markdown id:3ad36e86 tags:
%% Cell type:markdown id:3ad36e86 tags:
Um den Supertyp eines Typs zu erhalten, kann man `supertype` verwenden:
Um den Supertyp eines Typs zu erhalten, kann man `supertype` verwenden:
%% Cell type:code id:e666712d tags:
%% Cell type:code id:e666712d tags:
``` julia
``` julia
@showsupertype(Int64)
@showsupertype(Int64)
@showsupertype(Signed)
@showsupertype(Signed)
@showsupertype(Float16)
@showsupertype(Float16)
@showsupertype(Float32)
@showsupertype(Float32)
@showsupertype(Bool);
@showsupertype(Bool);
```
```
%% Cell type:code id:147db9b0 tags:
%% Cell type:code id:147db9b0 tags:
``` julia
``` julia
function print_supertypes(T::Type)
function print_supertypes(T::Type)
println("Supertypes of $T:")
println("Supertypes of $T:")
whileT!=Any
whileT!=Any
print(T," ---> ")
print(T," ---> ")
T=supertype(T)
T=supertype(T)
end
end
println(T)# Print Any, which is the ultimate supertype of all types
println(T)# Print Any, which is the ultimate supertype of all types
end
end
```
```
%% Cell type:code id:ed566f15 tags:
%% Cell type:code id:ed566f15 tags:
``` julia
``` julia
print_supertypes(Int64);
print_supertypes(Int64);
```
```
%% Cell type:code id:1462bc0c tags:
%% Cell type:code id:1462bc0c tags:
``` julia
``` julia
print_supertypes(Float64);
print_supertypes(Float64);
```
```
%% Cell type:markdown id:808b7968 tags:
%% Cell type:markdown id:808b7968 tags:
### Custom Abstract And Concrete Types
### Custom Abstract And Concrete Types
%% Cell type:markdown id:d16d0857 tags:
%% Cell type:markdown id:d16d0857 tags:
### Benutzerdefinierte Abstrakte und Konkrete Typen
### Benutzerdefinierte Abstrakte und Konkrete Typen
%% Cell type:markdown id:8cbad09b tags:
%% Cell type:markdown id:8cbad09b tags:
One can define custom abstract type by using `abstract type`:
One can define custom abstract type by using `abstract type`:
%% Cell type:markdown id:882efff3 tags:
%% Cell type:markdown id:882efff3 tags:
Man kann benutzerdefinierte abstrakte Typen mit `abstract type` definieren:
Man kann benutzerdefinierte abstrakte Typen mit `abstract type` definieren:
%% Cell type:code id:3ebf46f6 tags:
%% Cell type:code id:3ebf46f6 tags:
``` julia
``` julia
abstract type Animalend# Abstract type
abstract type Animalend# Abstract type
```
```
%% Cell type:markdown id:c1cceba1 tags:
%% Cell type:markdown id:c1cceba1 tags:
Then, some concrete types can be created as well:
Then, some concrete types can be created as well:
%% Cell type:markdown id:d63c0261 tags:
%% Cell type:markdown id:d63c0261 tags:
Dann können auch einige konkrete Typen erstellt werden:
Dann können auch einige konkrete Typen erstellt werden:
%% Cell type:code id:eaab065e tags:
%% Cell type:code id:eaab065e tags:
``` julia
``` julia
struct Dog<:Animal# Concrete type inheriting from Animal
struct Dog<:Animal# Concrete type inheriting from Animal
name::String
name::String
age::Int
age::Int
end
end
struct Cat<:Animal# Another concrete type inheriting from Animal
struct Cat<:Animal# Another concrete type inheriting from Animal
name::String
name::String
age::Int
age::Int
end
end
```
```
%% Cell type:markdown id:747d5555 tags:
%% Cell type:markdown id:747d5555 tags:
In this example, we create two concrete animal, `Dog` and `Cat`.
In this example, we create two concrete animal, `Dog` and `Cat`.
One can use subtypes to obtain all subtypes of either an abstract type or a concrete type.
One can use subtypes to obtain all subtypes of either an abstract type or a concrete type.
%% Cell type:markdown id:091a7905 tags:
%% Cell type:markdown id:091a7905 tags:
In diesem Beispiel erstellen wir zwei konkrete Tiere, `Dog` und `Cat`.
In diesem Beispiel erstellen wir zwei konkrete Tiere, `Dog` und `Cat`.
Man kann `subtypes` verwenden, um alle Subtypen eines abstrakten oder konkreten Typs zu erhalten.
Man kann `subtypes` verwenden, um alle Subtypen eines abstrakten oder konkreten Typs zu erhalten.
%% Cell type:code id:b8b7fca8 tags:
%% Cell type:code id:b8b7fca8 tags:
``` julia
``` julia
subtypes(Animal)
subtypes(Animal)
```
```
%% Cell type:markdown id:466cfcf7 tags:
%% Cell type:markdown id:466cfcf7 tags:
Again, using `isabstracttype` and `isconcretetype` we have
Again, using `isabstracttype` and `isconcretetype` we have
%% Cell type:markdown id:a2f3177d tags:
%% Cell type:markdown id:a2f3177d tags:
Wiederum können wir mit `isabstracttype` und `isconcretetype` überprüfen:
Wiederum können wir mit `isabstracttype` und `isconcretetype` überprüfen:
%% Cell type:code id:3eced325 tags:
%% Cell type:code id:3eced325 tags:
``` julia
``` julia
@showisabstracttype(Animal)
@showisabstracttype(Animal)
@showisabstracttype(Dog)
@showisabstracttype(Dog)
@showisabstracttype(Cat)
@showisabstracttype(Cat)
@showisconcretetype(Animal)
@showisconcretetype(Animal)
@showisconcretetype(Dog)
@showisconcretetype(Dog)
@showisconcretetype(Cat);
@showisconcretetype(Cat);
```
```
%% Cell type:markdown id:580bf73c tags:
%% Cell type:markdown id:580bf73c tags:
The type tree of `Animal` is:
The type tree of `Animal` is:
%% Cell type:markdown id:4b08f9f7 tags:
%% Cell type:markdown id:4b08f9f7 tags:
Der Typ-Baum von `Animal` ist:
Der Typ-Baum von `Animal` ist:
%% Cell type:code id:40debabd tags:
%% Cell type:code id:40debabd tags:
``` julia
``` julia
print_type_tree(Animal)
print_type_tree(Animal)
```
```
%% Cell type:markdown id:f4fb75fe tags:
%% Cell type:markdown id:f4fb75fe tags:
Now, we create two instances from the concrete types:
Now, we create two instances from the concrete types:
%% Cell type:markdown id:87e2a153 tags:
%% Cell type:markdown id:87e2a153 tags:
Jetzt erstellen wir zwei Instanzen von den konkreten Typen:
Jetzt erstellen wir zwei Instanzen von den konkreten Typen:
%% Cell type:code id:6f0f092f tags:
%% Cell type:code id:6f0f092f tags:
``` julia
``` julia
a_dog=Dog("Buddy",3)
a_dog=Dog("Buddy",3)
a_cat=Cat("Kitty",2)
a_cat=Cat("Kitty",2)
@showa_doga_cat;
@showa_doga_cat;
```
```
%% Cell type:markdown id:19797a26 tags:
%% Cell type:markdown id:19797a26 tags:
In Julia, the `isa` method is used to determine whether an instance is of a particular type, whether it is abstract or concrete:
In Julia, the `isa` method is used to determine whether an instance is of a particular type, whether it is abstract or concrete:
%% Cell type:markdown id:41ea3797 tags:
%% Cell type:markdown id:41ea3797 tags:
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:
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:
%% Cell type:code id:263461b1 tags:
%% Cell type:code id:263461b1 tags:
``` julia
``` julia
@showisa(a_dog,Dog)
@showisa(a_dog,Dog)
@showisa(a_dog,Animal)
@showisa(a_dog,Animal)
@showisa(a_dog,Cat)
@showisa(a_dog,Cat)
@showisa(a_cat,Cat);
@showisa(a_cat,Cat);
```
```
%% Cell type:markdown id:cbb0a853 tags:
%% Cell type:markdown id:cbb0a853 tags:
The method `typeof` is used to obtain the type of an instance:
The method `typeof` is used to obtain the type of an instance:
%% Cell type:markdown id:ee934bc9 tags:
%% Cell type:markdown id:ee934bc9 tags:
Die Methode `typeof` wird verwendet, um den Typ einer Instanz zu erhalten:
Die Methode `typeof` wird verwendet, um den Typ einer Instanz zu erhalten:
%% Cell type:code id:208aed02 tags:
%% Cell type:code id:208aed02 tags:
``` julia
``` julia
@showtypeof(a_dog)
@showtypeof(a_dog)
@showtypeof(a_cat);
@showtypeof(a_cat);
```
```
%% Cell type:markdown id:1be97baf tags:
%% Cell type:markdown id:1be97baf tags:
We can also get all supertypes of `Dog` and `Cat`:
We can also get all supertypes of `Dog` and `Cat`:
%% Cell type:markdown id:8dc6aef6 tags:
%% Cell type:markdown id:8dc6aef6 tags:
Wir können auch alle Supertypen von `Dog` und `Cat` erhalten:
Wir können auch alle Supertypen von `Dog` und `Cat` erhalten:
%% Cell type:code id:b3ca83e6 tags:
%% Cell type:code id:b3ca83e6 tags:
``` julia
``` julia
print_supertypes(Dog)
print_supertypes(Dog)
```
```
%% Cell type:code id:662a732f tags:
%% Cell type:code id:662a732f tags:
``` julia
``` julia
print_supertypes(Cat)
print_supertypes(Cat)
```
```
%% Cell type:markdown id:ff7efe19 tags:
%% Cell type:markdown id:ff7efe19 tags:
### Exercises
### Exercises
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.
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 tags:
%% Cell type:markdown id:d850444b tags:
### Übungen
### Übungen
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.
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.
In Julia concrete types are always a leaf of the type tree, i.e. they cannot be inherited from each other. For a C++ or Python person (as a few of us) this seems restrictive at first, but it takes away a lot of unnecessary complexity from the type hierarchy. We will not give further information now, the reason will be more clear at the end of this notebook.
In Julia concrete types are always a leaf of the type tree, i.e. they cannot be inherited from each other. For a C++ or Python person (as a few of us) this seems restrictive at first, but it takes away a lot of unnecessary complexity from the type hierarchy. We will not give further information now, the reason will be more clear at the end of this notebook.
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).
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 tags:
%% Cell type:markdown id:77bb1fe2 tags:
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.
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.
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).
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).
Multiple dispatch is probably the key feature of Julia that makes it different with respect to many other languages and give it the ability to be at the same time flexible and performant.
Multiple dispatch is probably the key feature of Julia that makes it different with respect to many other languages and give it the ability to be at the same time flexible and performant.
To fully understand the concept of multiple dispatch, we will use an analogy, we will pretend that a programming language is a tool to write a book of food recipes. A recipe combines a method of cooking (for example baking, frying) with an ingredient (for example potatoes, carrots, fish).
To fully understand the concept of multiple dispatch, we will use an analogy, we will pretend that a programming language is a tool to write a book of food recipes. A recipe combines a method of cooking (for example baking, frying) with an ingredient (for example potatoes, carrots, fish).
- The first possibility is to organize the book according to methods of cooking: each chapter explains in detail a method of cooking. For example, we will have **Chapter 1: baking**, **Chapter 2: frying** and so on. The drawback of this approach is that whenever we add a new ingredient, we have to change multiple chapters. This approach, focused on the action rather than on ingredients, is typical of functional programming languages.
- The first possibility is to organize the book according to methods of cooking: each chapter explains in detail a method of cooking. For example, we will have **Chapter 1: baking**, **Chapter 2: frying** and so on. The drawback of this approach is that whenever we add a new ingredient, we have to change multiple chapters. This approach, focused on the action rather than on ingredients, is typical of functional programming languages.
- The second possibility is to organize the book according to ingredients: each chapter focuses on one ingredient. For example, we will have **Chapter 1: potatoes**, **Chapter 2: fish** and so on. The drawback of this approach is that whenever we add a new recipe, we have again to change multiple chapters. This approach is focused on the ingredients (data) and it is typical of object-oriented programming, where we will have something like:
- The second possibility is to organize the book according to ingredients: each chapter focuses on one ingredient. For example, we will have **Chapter 1: potatoes**, **Chapter 2: fish** and so on. The drawback of this approach is that whenever we add a new recipe, we have again to change multiple chapters. This approach is focused on the ingredients (data) and it is typical of object-oriented programming, where we will have something like:
``` python
``` python
class potatoes()
class potatoes()
potatoes.bake()
potatoes.bake()
potatoes.fry()
potatoes.fry()
```
```
- Julia takes a third approach called **multiple dispatch** which decouples the action from the data. In our hypothetical recipe book, we will have chapters like **Chapter 1: baking potatoes**, **Chapter 2: frying potatoes**, **Chapter 3: baking fish**, **Chapter 4: frying fish** and so on. Each of the chapters will contain something like:
- Julia takes a third approach called **multiple dispatch** which decouples the action from the data. In our hypothetical recipe book, we will have chapters like **Chapter 1: baking potatoes**, **Chapter 2: frying potatoes**, **Chapter 3: baking fish**, **Chapter 4: frying fish** and so on. Each of the chapters will contain something like:
``` julia
``` julia
function baking(potatoes::Potatoes)
function baking(potatoes::Potatoes)
function frying(potatoes::Potatoes)
function frying(potatoes::Potatoes)
function baking(fish::Fish)
function baking(fish::Fish)
function frying(fish::Fish)
function frying(fish::Fish)
```
```
In this way, adding a new recipe for a specific kind of food does not require changing already written things.
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 tags:
%% Cell type:markdown id:64fc3a0b tags:
## Mehrfachdispatch (*multiple dispatch*)
## Mehrfachdispatch (*multiple dispatch*)
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.
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.
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).
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).
- 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.
- 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.
- 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:
- 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:
```julia
```julia
struct Kartoffeln
struct Kartoffeln
function backen()
function backen()
function braten()
function braten()
end
end
struct Fisch
struct Fisch
function backen()
function backen()
function braten()
function braten()
end
end
```
```
- 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:
- 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:
```julia
```julia
function backen(kartoffeln::Kartoffeln)
function backen(kartoffeln::Kartoffeln)
function braten(kartoffeln::Kartoffeln)
function braten(kartoffeln::Kartoffeln)
function backen(fisch::Fisch)
function backen(fisch::Fisch)
function braten(fisch::Fisch)
function braten(fisch::Fisch)
```
```
Auf diese Weise erfordert das Hinzufügen eines neuen Rezepts für eine bestimmte Art von Lebensmittel keine Änderungen an bereits geschriebenen Dingen.
Auf diese Weise erfordert das Hinzufügen eines neuen Rezepts für eine bestimmte Art von Lebensmittel keine Änderungen an bereits geschriebenen Dingen.
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:
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 tags:
%% Cell type:markdown id:1eda2f65 tags:
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:
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:
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:
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 tags:
%% Cell type:markdown id:13b4953e tags:
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:
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:
In both of these, the syntax `str::String` and `n::Integer` means that the respective method is only
In both of these, the syntax `str::String` and `n::Integer` means that the respective method is only
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:
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 tags:
%% Cell type:markdown id:ed42c2c2 tags:
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:
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:
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:
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 tags:
%% Cell type:markdown id:ed16db85 tags:
### Methoden
### Methoden
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:
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:
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.
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 tags:
%% Cell type:markdown id:12b5d667 tags:
### Abstrakte Typen und Mehrfachdispatch
### Abstrakte Typen und Mehrfachdispatch
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.
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.
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.
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 tags:
%% Cell type:markdown id:694b2921 tags:
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.
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.
This example really shows the power of Julia. Multiple dispatch is good for these reasons:
This example really shows the power of Julia. Multiple dispatch is good for these reasons:
- **Flexibilty:** it is possible to try out new things in a very fast way. We implement a new data type and we use the methods which are already there for abstract types.
- **Flexibilty:** it is possible to try out new things in a very fast way. We implement a new data type and we use the methods which are already there for abstract types.
- **Customization:** implementing custom behavior for our data types is easy, we simply need to add a custom method.
- **Customization:** implementing custom behavior for our data types is easy, we simply need to add a custom method.
- **Efficiency:** we can tune the specific methods to be super fast with our specific data type.
- **Efficiency:** we can tune the specific methods to be super fast with our specific data type.
%% Cell type:markdown id:7a6463aa tags:
%% Cell type:markdown id:7a6463aa tags:
Dieses Beispiel zeigt wirklich die Stärke von Julia. Mehrfachdispatch ist aus folgenden Gründen gut:
Dieses Beispiel zeigt wirklich die Stärke von Julia. Mehrfachdispatch ist aus folgenden Gründen gut:
- **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.
- **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.
- **Anpassungsfähigkeit:** Das Implementieren benutzerdefinierter Verhaltensweisen für unsere Datentypen ist einfach. Wir müssen einfach eine benutzerdefinierte Methode hinzufügen.
- **Anpassungsfähigkeit:** Das Implementieren benutzerdefinierter Verhaltensweisen für unsere Datentypen ist einfach. Wir müssen einfach eine benutzerdefinierte Methode hinzufügen.
- **Effizienz:** Wir können die spezifischen Methoden so abstimmen, dass sie mit unserem spezifischen Datentyp super schnell sind.
- **Effizienz:** Wir können die spezifischen Methoden so abstimmen, dass sie mit unserem spezifischen Datentyp super schnell sind.
Add some methods for `Animal`, `Dog` and `Cat` and other concrete type from the last exercise.
Add some methods for `Animal`, `Dog` and `Cat` and other concrete type from the last exercise.
%% Cell type:markdown id:0687c04d tags:
%% Cell type:markdown id:0687c04d tags:
### Übung
### Übung
Fügen Sie einige Methoden für `Animal`, `Dog` und `Cat` sowie andere konkrete Typen aus der letzten Übung hinzu.
Fügen Sie einige Methoden für `Animal`, `Dog` und `Cat` sowie andere konkrete Typen aus der letzten Übung hinzu.
%% Cell type:code id:6a45fa48 tags:
%% Cell type:code id:6a45fa48 tags:
``` julia
``` julia
# TODO: implement your code here.
# TODO: implement your code here.
```
```
%% Cell type:markdown id:ccf57f28 tags:
%% Cell type:markdown id:ccf57f28 tags:
## Dynamical typing and type deduction
## Dynamical typing and type deduction
%% Cell type:markdown id:4fb9457b tags:
%% Cell type:markdown id:4fb9457b tags:
## Dynamische Typisierung und Typableitung
## Dynamische Typisierung und Typableitung
%% Cell type:markdown id:85870a09 tags:
%% Cell type:markdown id:85870a09 tags:
In programming language theory type systems traditionally fall in two categories.
In programming language theory type systems traditionally fall in two categories.
In **dynamically typed** languages the type of a value or expression is inferred only at runtime,
In **dynamically typed** languages the type of a value or expression is inferred only at runtime,
which usually allows for more flexible code. Examples are Python or MATLAB. In contrast, so-called **statically-typed** languages (think FORTRAN or C++), require types to be already known before runtime when the program is compiled. This allows both to check more thoroughly for errors (which can manifest in mismatched types) and it usually brings a gain in performance because more things about the memory layout of the program is known at compile time. As a result, aspects such as vectorization, contiguous alignment of data, preallocation of memory can be leveraged more easily.
which usually allows for more flexible code. Examples are Python or MATLAB. In contrast, so-called **statically-typed** languages (think FORTRAN or C++), require types to be already known before runtime when the program is compiled. This allows both to check more thoroughly for errors (which can manifest in mismatched types) and it usually brings a gain in performance because more things about the memory layout of the program is known at compile time. As a result, aspects such as vectorization, contiguous alignment of data, preallocation of memory can be leveraged more easily.
Julia is kind of both.
Julia is kind of both.
%% Cell type:markdown id:f27eca4d tags:
%% Cell type:markdown id:f27eca4d tags:
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.
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.
Julia ist irgendwie beides.
Julia ist irgendwie beides.
%% Cell type:code id:3ef4e3d0 tags:
%% Cell type:code id:3ef4e3d0 tags:
``` julia
``` julia
x = Dog("Buddy", 4) # x is an Dog
x = Dog("Buddy", 4) # x is an Dog
@show typeof(x)
@show typeof(x)
x = Cat("Kitty", 3) # Now x is a Cat
x = Cat("Kitty", 3) # Now x is a Cat
@show typeof(x);
@show typeof(x);
```
```
%% Cell type:markdown id:a02c0a37 tags:
%% Cell type:markdown id:a02c0a37 tags:
Julia's strong emphasis on types is one of the reasons for its performance and flexibility.
Julia's strong emphasis on types is one of the reasons for its performance and flexibility.
When the code is precompiled before execution, the compiler has the information about the type of all the variables in the program. It will then search the best possible method for each of those. If a specific and highly efficient one is found, that will be used. If a specific one is missing, it will use the next possibility in the type tree, which will still work even if not as efficiently.
When the code is precompiled before execution, the compiler has the information about the type of all the variables in the program. It will then search the best possible method for each of those. If a specific and highly efficient one is found, that will be used. If a specific one is missing, it will use the next possibility in the type tree, which will still work even if not as efficiently.
**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.
**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 tags:
%% Cell type:markdown id:3e5a5e29 tags:
Julias starke Betonung von Typen ist einer der Gründe für ihre Leistungsfähigkeit und Flexibilität.
Julias starke Betonung von Typen ist einer der Gründe für ihre Leistungsfähigkeit und Flexibilität.
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.
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.
**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.
**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 tags:
%% Cell type:markdown id:27812692 tags:
### Three more facts about Julia types:
### Three more facts about Julia types:
- In Julia all types are the same. For example, there is no difference between `Int32` and `String`, even though the first has a direct mapping to low-level instructions in the CPU and the latter has not (contrast this with e.g. C++).
- In Julia all types are the same. For example, there is no difference between `Int32` and `String`, even though the first has a direct mapping to low-level instructions in the CPU and the latter has not (contrast this with e.g. C++).
- The `Nothing` type with the single instance `nothing` is the Julia equivalent to `void` in C++ or `None` in Python. It often represents that a function does not return anything or that a variable has not been initialised.
- The `Nothing` type with the single instance `nothing` is the Julia equivalent to `void` in C++ or `None` in Python. It often represents that a function does not return anything or that a variable has not been initialised.
- `Any` is the root of the type tree: Any type in Julia is a subtype of `Any`.
- `Any` is the root of the type tree: Any type in Julia is a subtype of `Any`.
%% Cell type:markdown id:869f5fbc tags:
%% Cell type:markdown id:869f5fbc tags:
### Drei weitere Fakten über Julia-Typen:
### Drei weitere Fakten über Julia-Typen:
- 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++).
- 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++).
- 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.
- 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.
- `Any` ist die Wurzel des Typbaums: Jeder Typ in Julia ist ein Untertyp von `Any`.
- `Any` ist die Wurzel des Typbaums: Jeder Typ in Julia ist ein Untertyp von `Any`.
This exercise is about writing a custom data type for polynomials, a set of constructors for them, and functions to perform operations on them. **Note:** writing custom polynomials in this way is neither efficient nor convenient, but it is a great example of the topics seen so far.
- Implement a new abstract type `AbstractPolynomial`. Then, implement a few concrete subtypes, `PolynomialDegree0`, `PolynomialDegree1`, `PolynomialDegree2` and `PolynomialArbitraryDegree`. **Tip:** use a dictionary to store the coefficients and do it in a consistent way between the various subtypes: you can use the power of `x` as the key for the coefficient value.
- Write a constructor for each of them which takes as input the coefficients. **Tip:** use `args::Real...` to gather an arbitrary number of arguments, specifying the type is important for avoiding ambiguity when calling with one argument (try not specyifing `Real` to see the problem).
- Write a function `Polynomial` with multiple methods: depending on the number of arguments, it should call the correct constructor. **Tips:** you can use the shorthand `Polynomial(c0) = PolynomialDegree0(c0)` to write more concise code, and you should again use `args...` to support an arbitrary amount of arguments.
- Implement a method of the `+` function which sums together two `AbstractPolynomial`. It should work with any combination of the concrete types. It should also use a loop over the coefficients. **Note:** implementing a method for a function of the core library requires first to import it `import Base.:+`.
- Implement some more methods of the `+` library which sum together polynomials of low degree, they should not use a for loop.
- Last, benchmark the `+` function for two `PolynomialDegree1` polynomials and for two `PolynomialArbitraryDegree` of degree 1. **Tips:** generate random coefficients using `rand()`, repeat the process a few thousands times to get a measurable run time, use the macro `@time` to get the time.
Diese Übung befasst sich mit dem Schreiben eines benutzerdefinierten Datentyps für Polynome, einer Reihe von Konstruktoren dafür und Funktionen zum Durchführen von Operationen an ihnen. **Hinweis:** Das Schreiben benutzerdefinierter Polynome auf diese Weise ist weder effizient noch bequem, aber es ist ein gutes Beispiel für die bisher behandelten Themen.
- Implementieren Sie einen neuen abstrakten Datentyp `AbstractPolynomial`. Dann implementieren Sie einige konkrete Untertypen, `PolynomialDegree0`, `PolynomialDegree1`, `PolynomialDegree2` und `PolynomialArbitraryDegree`. **Tipp:** Verwenden Sie ein Wörterbuch, um die Koeffizienten auf konsistente Weise zwischen den verschiedenen Untertypen zu speichern: Sie können die Potenz von `x` als Schlüssel für den Koeffizientenwert verwenden.
Implement a new abstract type `Polynomial` which is a subtype of `Number`.
- Schreiben Sie einen Konstruktor für jeden von ihnen, der die Koeffizienten als Eingabe erhält. **Tipp:** Verwenden Sie `args::Real...`, um eine beliebige Anzahl von Argumenten zu sammeln. Die Angabe des Typs ist wichtig, um Unklarheiten beim Aufruf mit einem Argument zu vermeiden (versuchen Sie, `Real` nicht anzugeben, um das Problem zu sehen).
TO BE FINISHED
- Schreiben Sie eine Funktion `Polynomial` mit mehreren Methoden: Abhängig von der Anzahl der Argumente sollte sie den richtigen Konstruktor aufrufen. **Tipps:** Sie können die Kurzform `Polynomial(c0) = PolynomialDegree0(c0)` verwenden, um den Code kürzer zu schreiben, und Sie sollten erneut `args...` verwenden, um eine beliebige Anzahl von Argumenten zu unterstützen.
- Implementieren Sie eine Methode der `+` Funktion, die zwei `AbstractPolynomial` zusammenzählt. Es sollte mit jeder Kombination der konkreten Typen funktionieren. Es sollte auch eine Schleife über die Koeffizienten verwenden. **Hinweis:** Das Implementieren einer Methode für eine Funktion der Kernbibliothek erfordert zunächst das Importieren von `import Base.:+`.
- Implementieren Sie einige weitere Methoden der `+`-Bibliothek, die Polynome niedriger Ordnung zusammenzählen. Diese sollten keine Schleife verwenden.
- Zuletzt führen Sie eine Leistungsbewertung der `+` Funktion für zwei `PolynomialDegree1`-Polynome und für zwei `PolynomialArbitraryDegree`-Polynome vom Grad 1 durch. **Tipps:** Generieren Sie zufällige Koeffizienten mit `rand()`, wiederholen Sie den Vorgang einige Tausend Mal, um eine messbare Laufzeit zu erhalten, verwenden Sie die Makro `@time`, um die Zeit zu messen.